-
继承Thread类;
-
重写run()方法;
-
调用start()开启线程;
public class TestThread1 extends Thread{
@Override
public void run(){
for (int i = 0; i < 200; i++) {
System.out.println("我在看代码~~"+i);
}
}
public static void main(String[] args) {
TestThread1 testThread1 = new TestThread1();
testThread1.start();
for (int i = 0; i < 1000; i++) {
System.out.println("我在学习线程"+i);
}
}
}
方式二
-
实现Runnable接口;
-
重写run()方法;
-
通过new Thread(自定义线程对象).start()启动线程;
public class TestThread2 implements Runnable{
@Override
public void run(){
//run方法线程体
for (int i = 0; i < 200; i++) {
System.out.println("我在看代码~~"+i);
}
}
public static void main(String[] args) {
//创建runnable接口的实现类对象
TestThread2 testThread2 = new TestThread2();
new Thread(testThread2).start();
for (int i = 0; i < 1000; i++) {
System.out.println("我在学习线程~~"+i);
}
}
}
方式三(了解)
-
实现Callable接口,需要返回值类型;
-
重写call()方法,需要抛出异常;
-
创建目标对象;
-
创建执行服务: ExecutorService service = Executors.newCachedThreadPool();
-
提交执行: Future
r1 = service.submit(testThread4); -
获取结果:boolean rs1 = r1.get();
-
关闭服务:service.shutdown();
public class TestThread4 implements Callable
{ @Override public Boolean call() throws Exception{ for (int i = 0; i < 10; i++) { System.out.println(Thread.currentThread().getName()+"在学习线程~~"+i); } return true; } public static void main(String[] args) throws ExecutionException, InterruptedException { //创建自定义线程对象 TestThread4 testThread4 = new TestThread4(); //创建执行服务 ExecutorService service = Executors.newFixedThreadPool(3);; //提交执行 Future r1 = service.submit(testThread4); Future r2 = service.submit(testThread4); Future r3 = service.submit(testThread4); //获取结果 boolean rs1 = r1.get(); boolean rs2 = r2.get(); boolean rs3 = r3.get(); System.out.println(rs1); System.out.println(rs2); System.out.println(rs3); //关闭服务 service.shutdown(); } }
-
任何接口,如果只包含唯一一个抽象方法,那么它就是一个函数式接口.
-
对于函数式接口,我们可以通过lambda表达式来创建该接口的对象.
public class TestLambda { public static void main(String[] args) { ILike like = null; //通过匿名内部类 like = new ILike() { @Override public void lambda(int a) { System.out.println("i like lambda-->"+a); } }; like.lambda(521); //lambda表达式 like = (int a ) -> { System.out.println("i like lambda1-->"+a); }; like.lambda(521); //简化式写法 like = a -> { System.out.println("i like lambda2-->"+a); }; like.lambda(521); } } //定义一个函数式接口 interface ILike{ void lambda(int a); } //实现类 class Like implements ILike{ @Override public void lambda(int a) { System.out.println("i like lambda-->"+a); } }
-
接口是函数式接口(接口里面只有一个抽象方法);
-
多个参数也可以去掉参数类型,要去掉就全去掉,必须加上括号;
线程停止
public class TestStop implements Runnable{
//定义标志位
private boolean flag = true;
@Override
public void run() {
int i = 0;
while (flag) {
System.out.println("Thread run...." + i++);
}
}
//定义一个停止方法
public void stop(){
this.flag = false;
}
public static void main(String[] args) {
TestStop testStop = new TestStop();
new Thread(testStop).start();
for (int i = 0; i < 1000; i++) {
System.out.println("main" + i);
if (i == 900){
//调用stop方法切换标志位,停止线程
testStop.stop();
System.out.println("Thread is stop....");
}
}
}
}
线程休眠
模拟网络延时
public class TestSleep implements Runnable{
//票数
private int ticketNums = 1;
@Override
public void run() {
while (true) {
synchronized (TestSleep.class) {
if (ticketNums > 20) {
break;
}
//模拟延时
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + "-->拿到了第" + ticketNums++ + "票");
}
}
}
public static void main(String[] args) {
TestSleep ticket = new TestSleep();
new Thread(ticket,"小明").start();
new Thread(ticket,"老师").start();
new Thread(ticket,"黄牛").start();
}
}
模拟倒计时
public class TestSleep2 {
public static void main(String[] args) {
//打印当前时间
Date startTime = new Date(System.currentTimeMillis());//获取系统当前时间
while (true){
try {
Thread.sleep(1000);
System.out.println(new SimpleDateFormat("HH:mm:ss").format(startTime));
startTime = new Date(System.currentTimeMillis());//更新当前时间
} catch (InterruptedException e) {
e.printStackTrace();
}
}
//调用方法
}
//模拟倒计时
public static void numDown() throws InterruptedException {
int num = 10;
while (true){
Thread.sleep(1000);
System.out.println(num--);
if (num <= 0){
break;
}
}
}
}
线程同步
并发: 多个线程操作同一个资源;
线程安全需要加锁(同步锁);
同步锁public class UnsafeBuyTicket {
public static void main(String[] args) {
BuyTicket station = new BuyTicket();
new Thread(station,"我").start();
new Thread(station,"黄牛").start();
new Thread(station,"你").start();
}
}
class BuyTicket implements Runnable{
//票
private int ticketNums = 10;
boolean flag = true; //外部停止方式
@Override
public void run() {
//买票
while (flag){
try {
buy();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
private void buy() throws InterruptedException {
synchronized (this){
//判断是否有票
if (ticketNums <= 0){
flag = false;
return;
}
Thread.sleep(100);
//买票
System.out.println(Thread.currentThread().getName()+"拿到"+ticketNums--);
}
}
}
死锁
多个线程各自占有一些共享资源,并且相互等待其他线程占有的资源才能运行,而导致两个或者多个线程都在等待对方释放资源,都停止执行的情形,某一个同步块同时拥有"两个以上对象的锁"时,就可能会发生"死锁"的问题.
public class DeadLock {
public static void main(String[] args) {
Makeup g1 = new Makeup(0,"小红");
Makeup g2 = new Makeup(1,"小兰");
g1.start();
g2.start();
}
}
//口红
class Lipstick{
}
//镜子
class Mirror{
}
class Makeup extends Thread{
//需要的资源只有一份,用static来保证只有一份
static Lipstick lipstick = new Lipstick();
static Mirror mirror = new Mirror();
int choice;//选择
String girlName;//使用人
Makeup(int choice,String girlName){
this.choice = choice;
this.girlName = girlName;
}
@Override
public void run() {
//化妆
try {
makeup();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
//化妆,互相持有对方的锁,就是需要先拿到对方的资源
private void makeup() throws InterruptedException {
if (choice == 0){
synchronized (lipstick){//获得口红的锁
System.out.println(this.girlName+"获得口红的锁");
Thread.sleep(1000);
synchronized (mirror){//一秒后获得镜子的锁
System.out.println(this.girlName+"获得镜子的锁");
}
}
}else {
synchronized (mirror){//获得镜子的锁
System.out.println(this.girlName+"获得镜子的锁");
Thread.sleep(2000);
synchronized (lipstick){//两秒后获得口红的锁
System.out.println(this.girlName+"获得口红的锁");
}
}
}
}
}
死锁避免方法
产生死锁的四个必要条件:
-
互斥条件: 一个资源每次只能被一个进程使用;
-
请求与保持条件: 一个进程因请求资源而阻塞时,对已获得的资源保持不放;
-
不剥夺条件: 进程已获得的资源,在未使用完之前,不能强行剥夺;
-
循环等待条件: 若干进程之间形成一种头尾相接的循环等待资源关系;
避免死锁
public class DeadLock {
public static void main(String[] args) {
Makeup g1 = new Makeup(0,"小红");
Makeup g2 = new Makeup(1,"小兰");
g1.start();
g2.start();
}
}
//口红
class Lipstick{
}
//镜子
class Mirror{
}
class Makeup extends Thread{
//需要的资源只有一份,用static来保证只有一份
static Lipstick lipstick = new Lipstick();
static Mirror mirror = new Mirror();
int choice;//选择
String girlName;//使用人
Makeup(int choice,String girlName){
this.choice = choice;
this.girlName = girlName;
}
@Override
public void run() {
//化妆
try {
makeup();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
//化妆,互相持有对方的锁,就是需要先拿到对方的资源
private void makeup() throws InterruptedException {
if (choice == 0){
synchronized (lipstick){//获得口红的锁
System.out.println(this.girlName+"获得口红的锁");
Thread.sleep(1000);
}
synchronized (mirror){//一秒后获得镜子的锁
System.out.println(this.girlName+"获得镜子的锁");
}
}else {
synchronized (mirror){//获得镜子的锁
System.out.println(this.girlName+"获得镜子的锁");
Thread.sleep(2000);
}
synchronized (lipstick){//两秒后获得口红的锁
System.out.println(this.girlName+"获得口红的锁");
}
}
}
}
Lock锁
-
从JDK 5.0开始,java提供了更强大的线程同步机制----通过显示定义同步锁对象来实现同步,同步锁使用Lock对象充当;
-
java.util.concurrent.locks.Lock接口是控制多个线程对共享资源进行访问的工具;锁提供了对共享资源的独占访问,每次只能有一个线程对Lock对象加锁,线程开始访问共享资源之前应先获得Lock对象;
-
ReentrantLock(可重入锁) 类实现了Lock,他拥有与synchronized 相同的并发性和内存语义,在实现线程安全的控制中,比较常用的是ReentrantLock,可以显示加锁、释放锁;
public class TestLock {
public static void main(String[] args) {
TestLock2 testLock2 = new TestLock2();
new Thread(testLock2).start();
new Thread(testLock2).start();
new Thread(testLock2).start();
}
}
class TestLock2 implements Runnable{
int ticketNums = 20;
//定义lock锁
private final ReentrantLock lock = new ReentrantLock();
@Override
public void run() {
while (true) {
try {
lock.lock();//加锁
if (ticketNums > 0) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(ticketNums--);
} else {
break;
}
}finally {
lock.unlock();//解锁
}
}
}
}
synchronized 与 Lock 的对比
-
Lock是显示锁(手动开启和关闭锁,别忘记关闭锁) synchronized是隐式锁,出了作用域自动释放;
-
Lock只有代码块,synchronized有代码块锁和方法锁;
-
使用Lock锁,JVM将花费较少的时间来调度线程,性能更好;并且具有更好的扩展性(提供更多的子类);
-
优先使用顺序:
-
Lock > 同步代码块(已经进入了方法体,分配了相应资源) > 同步方法(在方法体之外)
-
-
应用场景: 生产者和消费者问题
-
假设仓库中只能存放一件产品,生产者将生产出来的产品放入仓库,消费者将仓库中产品取走消费;
-
如果仓库中没有产品,则生产者将产品放入仓库,否则停止生产并等待,直到仓库中的产品被消费者取走为止;
-
如果仓库中放有产品,则消费者可以将产品取走消费,否则停止消费并等待,直到仓库中再次放入产品为止;
-
这是一个线程同步问题,生产者和消费者共享同一个资源,并且生产者和消费者之间相互依赖,互为条件;
-
对于生产者,没有生产产品之前,要通知消费者等待;而生产了产品之后,又需要马上通知消费者消费;
-
对于消费者,在消费之后,要通知生产者已经结束消费,需要生产新的产品以供消费;
-
在生产者消费者问题中,仅有synchronized是不够的
-
synchronized 可阻止并发更新同一个共享资源,实现了同步;
-
synchronized 不可能用来实现不同线程之间的消息传递(通信);
-
java提供了几个方法解决线程之间的通信问题
解决方式一
public class TestPC {
public static void main(String[] args) {
SynContainer container = new SynContainer();
new Productor(container).start();
new Consumer(container).start();
}
}
//生产者
class Productor extends Thread{
SynContainer container;
public Productor(SynContainer container){
this.container = container;
}
//生产
@Override
public void run() {
for (int i = 0; i < 100; i++) {
container.push(new Chicken(i));
System.out.println("生产了"+i+"只鸡");
}
}
}
//消费者
class Consumer extends Thread{
SynContainer container;
public Consumer(SynContainer container){
this.container = container;
}
//消费
@Override
public void run() {
for (int i = 0; i < 100; i++) {
System.out.println("消费了-->"+container.pop().id+"只鸡");
}
}
}
//产品
class Chicken{
int id;
public Chicken(int id) {
this.id = id;
}
}
//缓冲区
class SynContainer{
//需要一个容器大小
Chicken[] chickens = new Chicken[10];
//容器计数器
int count = 0;
//生产者放入产品
public synchronized void push(Chicken chicken){
//如果容器满了,需要等待消费者消费
if (count == chickens.length){
//通知消费者消费,生产等待
try {
this.wait();
}catch (Exception e){
e.printStackTrace();
}
}
//如果没有满,我们就需要丢入产品
chickens[count] = chicken;
count++;
//可以通知消费者消费了
this.notifyAll();
}
//消费者消费产品
public synchronized Chicken pop(){
//判断能否消费
if (count == 0 ){
//等待生产者生产,消费者等待
try {
this.wait();
}catch (Exception e){
e.printStackTrace();
}
}
//如果可以消费
count--;
Chicken chicken = chickens[count];
//吃完了,通知生产者生产
this.notifyAll();
return chicken;
}
}
解决方式二
并发协作模型: 生产者/消费者模式 --->信号灯法
public class TestPC2 {
public static void main(String[] args) {
TV tv = new TV();
new Player(tv).start();
new Watcher(tv).start();
}
}
//生产者 -->演员
class Player extends Thread{
TV tv;
public Player(TV tv){
this.tv = tv;
}
@Override
public void run() {
for (int i = 0; i < 20; i++) {
if (i%2 == 0){
this.tv.play("快乐大本营");
}else {
this.tv.play("抖音;记录人家的美好生活");
}
}
}
}
//消费者 -->观众
class Watcher extends Thread{
TV tv;
public Watcher(TV tv){
this.tv = tv;
}
@Override
public void run() {
for (int i = 0; i < 20; i++) {
tv.watch();
}
}
}
//产品 -->节目
class TV{
//演员表演,观众等待
//观众观看,演员等待
String voice; //表演的节目
boolean flag = true;
//表演
public synchronized void play(String voice){
if (!flag){
try {
this.wait();
}catch (Exception e){
e.printStackTrace();
}
}
System.out.println("演员表演了"+voice);
//通知观众观看
this.notifyAll();//通知唤醒
this.voice = voice;
this.flag = !this.flag;
}
//观看
public synchronized void watch(){
if (flag){
try {
this.wait();
}catch (Exception e){
e.printStackTrace();
}
}
System.out.println("观众观看了"+voice);
//通知演员表演
this.notifyAll();
this.flag = !this.flag;
}
}
线程池
-
背景: 经常创建和销毁、使用量特别大的资源,比如并发情况下的线程,对性能影响很大。
-
思路:提前创建好多个线程,放入线程池中,使用时直接获取,使用完放回池中。可以避免频繁创建销毁、实现重复利用。类似生活中的公共交通工具。
-
好处:
-
提高响应速度(减少了创建新线程的时间)
-
降低资源消耗(重复利用线程池中线程,不需要每次都创建)
-
便于线程管理(....)
-
corePoolSize: 核心池的大小
-
maxximumPoolSize: 最大线程数
-
keepAliveTime: 线程没有任务时最多保持多长时间后会终止
-
-
public class TestPool {
public static void main(String[] args) {
//创建服务,创建线程池
//newFixedThreadPool 参数为: 线程池大小
ExecutorService service = Executors.newFixedThreadPool(10);
//执行
service.execute(new MyThread());
service.execute(new MyThread());
service.execute(new MyThread());
//关闭服务
service.shutdown();
}
}
class MyThread implements Runnable{
@Override
public void run() {
System.out.println(Thread.currentThread().getName());
}
}
-
JDK 5.0提供了线程池相关API: ExecutorService 和 Executors
-
ExecutorService: 真正的线程池接口;常见子类ThreadPoolExecutor
-
void execute(Runnable command): 执行任务/命令,没有返回值,一般用来执行Runnable
-
Future submit(Callable task): 执行任务,有返回值,一般又来执行Callable -
void shutdown(): 关闭连接池
-
-
Executors: 工具类、线程池的工厂类,用于创建并返回不同类型的线程池



