java 多线程(wait/notify/notifyall)

时间:2023-03-09 06:03:44
java 多线程(wait/notify/notifyall)
package com.example;

public class App {
/* wait\notify\notifyAll 都属于object的内置方法
* wait: 持有该对象的线程把该对象的控制权交出
notify: 通知某个正在等待该对象控制权的线程可以继续运行
notifyAll: 通知所有等待该对象控制权的线程继续运行 */
public static void main(String[] args) { MyThread mt = new MyThread();
mt.start();
//调用wait时,必须保证对该对象具有控制权,因此需要加synchronized
synchronized(mt){
try {
mt.wait();
} catch (InterruptedException e) {
e.printStackTrace();
} System.out.println(mt.total);
}
}
}
package com.example;

public class MyThread extends Thread {
int total = 0; public void run() {
//调用notify时,必须保证对该对象具有控制权,因此需要加synchronized
synchronized (this) {
for (int i = 0; i < 100; i++) {
total += i;
}
notify();
}
}
}