java多线程wait与notifyAll在具体代码中的运用原理(据说很多人都是半懂的哦)
wait与notifyAll
wait和notify/notifyAll的实现机制
Java的Object类中提供一个基于native实现的wait和notify线程间通信的方法。
- 什么时候需要使用wait和notify?
多个线程共享同一个资源,但是他们的任务却不相同。 - 线程之间的通信?
多个线程在共享同一个资源的时候,但是他们任务不相同,
通过一定的手动使得线程能够有效的利用共享资源,
就需要使用等待/唤醒机制
等待/唤醒机制涉及到的方法
<1> wait(): 等待,导致当前线程等待,直到另一个线程调用该对象的 notify()方法或
notifyAll()方法
<2> notify(): 唤醒,唤醒正在等待对象监视器的单个线程。 (调用1次方法只能唤醒1个,而
且是任意)
<3> notifyAll() 唤醒正在等待对象监视器的所有线程。
[所谓唤醒,让进去等待状态的线程重新获取执行资格]
“注意:这些方法必须在 synchronized的方法或者代码块内使用。” - 【面试题】 发现wait,notify,notifyAll方法不在Thread类中定义的
而是在Object类中定义的,为什么这些操作线程的方法定义
Object类中?
回答: 因为这些方法在使用的时候,必须要标明所属的对象的锁
而锁可以锁任意对象,“任意对象”只能使用Object表示。
所以定义在Object类中
运用
还是不懂的话可以去看看这个代码,实际运用也就是这样了
package com.teacher;
//编写一个程序,启动三个线程,三个线程的ID分别是A,B,C;
//每个线程将自己的ID值在屏幕上打印5遍,打印顺序是ABCABC...
public class T4 {
private static int flag = 0; // 0[printA] 1[printB] 2[printC]
public synchronized void printA() {
try {
for (int i = 1; i <= 5; i++) {
System.out.println("------printA方法----------");
// 判断是否不打印A
while (true) {
System.out.println("判断flag==0" + (flag == 0));
if (flag == 0) {
break;
}
System.out.println("------A---等待-------");
this.wait();
System.out.println("------A---唤醒-------");
}
System.out.println(Thread.currentThread().getName());
flag = 1;
this.notifyAll();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public synchronized void printB() {
try {
for (int i = 1; i <= 5; i++) {
System.out.println("------printB方法----------");
// 判断是否不打印A
while (true) {
System.out.println("判断flag==1" + (flag == 1));
if (flag == 1) {
break;
}
System.out.println("------B---等待-------");
this.wait();
System.out.println("------B---唤醒-------");
}
System.out.println(Thread.currentThread().getName());
flag = 2;
this.notifyAll();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public synchronized void printC() {
try {
for (int i = 1; i <= 5; i++) {
System.out.println("------printC方法----------");
// 判断是否不打印A
while (true) {
System.out.println("判断flag==2" + (flag == 2));
if (flag == 2) {
break;
}
System.out.println("------C---等待-------");
this.wait();
System.out.println("------C---唤醒-------");
}
System.out.println(Thread.currentThread().getName());
flag = 0;
this.notifyAll();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
T4 obj = new T4(); // 为什么创建这个对象,因为需要调用这个T4类中非静态方法
new Thread(() -> obj.printA(), "A").start();
new Thread(() -> obj.printB(), "B").start();
new Thread(() -> obj.printC(), "C").start();
}
}
小提示:notifyAll唤醒了其他线程之后会依旧以执行当前线程为主,当前线程执行完之后或者处于阻塞状态时才会让其他重新获得执行资格的线程去抢占。