多线程练习-顺序打印
wait和notify的使用推荐看通过wait和notify来协调线程执行顺序
题目
有三个线程,线程名称分别为:a,b,c。
每个线程打印自己的名称。
需要让他们同时启动,并按 c,b,a的顺序打印
代码及其注释
public class Demo4 {private static Object locker1=new Object();private static Object locker2=new Object();private static Object locker3=new Object();public static void main(String[] args) throws InterruptedException {//线程aThread a=new Thread(()->{//不知道当前是否到了打印a的时间,先进行阻塞等待synchronized(locker1){try {locker1.wait();} catch (InterruptedException e) {throw new RuntimeException(e);}}//被唤醒就打印a(当前线程的名称)System.out.print(Thread.currentThread().getName());},"a");Thread b=new Thread(()->{//不知道当前是否到了打印b的时间,先进行阻塞等待synchronized(locker2){try {locker2.wait();} catch (InterruptedException e) {throw new RuntimeException(e);}}//被唤醒就打印b(当前线程的名称)System.out.print(Thread.currentThread().getName());//打印b了以后要唤醒打印a的线程synchronized(locker1){locker1.notify();}},"b");Thread c=new Thread(()->{//不知道当前是否到了打印c的时间,先进行阻塞等待synchronized(locker3){try {locker3.wait();} catch (InterruptedException e) {throw new RuntimeException(e);}}//被唤醒就打印c(当前线程的名称)System.out.print(Thread.currentThread().getName());//打印c了以后要唤醒打印b的线程synchronized(locker2){locker2.notify();}},"c");a.start();b.start();c.start();//不能才启动线程c就准备进行唤醒,因为可能locker3在调用notify方法唤醒时,在c线程中locker3都还没有调用wait方法进入阻塞等待//此处唤醒就会落空,当过了一会locker3调用wait方法进入阻塞等待后又没有程序去唤醒了,程序就会卡死Thread.sleep(1000);//一开始要打印c所以在主线程中唤醒打印c的线程synchronized (locker3){locker3.notify();}}
}