WAITING 等待唤醒状态(线程之间的通信)
进入Timewaiting(计时等待)有两法:
- sleep(), 线程睡醒后进入Runable/阻塞状态
- wait(long m), 结束后没有被唤醒,会自动醒来
只有锁对象才能调用wait方法和notify方法
public class WaitAndNotify {
public static void main(String[] args) {
//创建锁对象
Object obj = new Object();
//顾客线程
new Thread() {
@Override
public void run() {
//保证wait和notify只能有一个执行
synchronized (obj) {
System.out.println("买多少包子");
//调用wait方法,因为父类没有throw异常,所以只能用try...catch
try {
obj.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
//唤醒之后执行的代码
System.out.println("包子已经做好,开吃");
}
}
}.start();
//老板线程
new Thread() {
@Override
public void run() {
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (obj) {
System.out.println("已经做好了");
obj.notify();
}
}
}.start();;
}
}
唤醒(2法):
- notify()唤醒单个
- notifyAll()唤醒全部
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。