Object类中wait带有参方法和notifyAll方法以及线程间通信
Object类中wait带有参方法和notifyAll方法
进入到TimeWaiting(计时等待)有两种方式
1.使用sleep(long m)方法,在毫秒值结束之后,线程睡醒进入到Runnadle/Blocked状态
2.使用wait(long m)方法,wait方法如果在毫秒值结束之后,还没有被notify唤醒,就会自动醒来
唤醒的方法:
void notify() 唤醒在此对象监听器上等待的单个线程
public class demg_09 { public static void main(String[] args) { //创建锁对象,唯一 Object obj = new Object(); //创建顾客线程 new Thread(){ @Override public void run() { while (true){ synchronized (obj){ System.out.println("01告知老板要的包子的种类和数量"); try { obj.wait();//等待 唤醒 } catch (InterruptedException e) { e.printStackTrace(); } //唤醒之后执行代码 System.out.println("包子已经做好了,01哥们吃吧"); System.out.println("--------------------------------"); } } } }.start(); //创建顾客线程 new Thread(){ @Override public void run() { while (true){ synchronized (obj){ System.out.println("02告知老板要的包子的种类和数量"); try { obj.wait();//等待 唤醒 } catch (InterruptedException e) { e.printStackTrace(); } //唤醒之后执行代码 System.out.println("包子已经做好了,02哥们吃吧"); System.out.println("--------------------------------"); } } } }.start(); //创建老板线程 new Thread(){ @Override public void run() { while (true){ synchronized (obj){ try { Thread.sleep(5000); } catch (InterruptedException e) { e.printStackTrace(); } synchronized (obj){ System.out.println("老板5秒钟会后做好包子,告知顾客,可以吃了"); obj.notify();//有多个等待线程,随机唤醒一个 // o.notifyAll();//唤醒所有等待的线程 } } } } }.start(); } }
运行结果:(一次只能输出单个线程)

void notifyAll() 唤醒在此对象监听器上等待的所有线程
public class demg_09 { public static void main(String[] args) { //创建锁对象,唯一 Object obj = new Object(); //创建顾客线程 new Thread(){ @Override public void run() { while (true){ synchronized (obj){ System.out.println("01告知老板要的包子的种类和数量"); try { obj.wait();//等待 唤醒 } catch (InterruptedException e) { e.printStackTrace(); } //唤醒之后执行代码 System.out.println("包子已经做好了,01哥们吃吧"); System.out.println("--------------------------------"); } } } }.start(); //创建顾客线程 new Thread(){ @Override public void run() { while (true){ synchronized (obj){ System.out.println("02告知老板要的包子的种类和数量"); try { obj.wait();//等待 唤醒 } catch (InterruptedException e) { e.printStackTrace(); } //唤醒之后执行代码 System.out.println("包子已经做好了,02哥们吃吧"); System.out.println("--------------------------------"); } } } }.start(); //创建老板线程 new Thread(){ @Override public void run() { while (true){ try { Thread.sleep(5000); } catch (InterruptedException e) { e.printStackTrace(); } synchronized (obj){ System.out.println("老板5秒钟会后做好包子,告知顾客,可以吃了"); // obj.notify();//有多个等待线程,随机唤醒一个 obj.notifyAll();//唤醒所有等待的线程 } } } }.start(); } }
运行结果:(唤醒所有在等待的线程)

notifyAll方法以及线程间通信
概念:多个线程在处理同一个资源多线程之间可以进行合作,但是处理的动作(线程的任务)却不同
比如:线程A用来生成包子的,线程B用来吃包子的,包子可以理解为同一资源,线程A与线程B处理的动作,一个是生产,一个是消费,那么线程A与线程B之间就存在线程通信问题


浙公网安备 33010602011771号