标签:public 概念 demo lis one object static 注释 cep
1、我们先验证下wait可以用notify和notifyAll来唤醒
如下测试代码:
public class WaitSleepDemo {
public static void main(String[] args) {
final Object lock = new Object();
new Thread(new Runnable() {
@Override
public void run() {
System.out.println("thread A is waiting to get lock");
synchronized (lock){
try {
System.out.println("thread A get lock");
Thread.sleep(20);
System.out.println("thread A do wait method");
//无限期的等待
lock.wait();
//Thread.sleep(1000);
System.out.println("thread A is done");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}).start();
//为了让Thread A 先于Thread B执行
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
new Thread(new Runnable() {
@Override
public void run() {
System.out.println("thread B is waiting to get lock");
synchronized (lock){
try {
System.out.println("thread B get lock");
System.out.println("thread B is sleeping 10 ms");
Thread.sleep(10);
// lock.wait(10);
System.out.println("thread B is done");
//这句注释掉,thread A is done就不会被打印
lock.notify(); // lock.notifyAll();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}).start();
}
}
执行结果:
thread A is waiting to get lock thread A get lock thread B is waiting to get lock thread A do wait method thread B get lock thread B is sleeping 10 ms thread B is done thread A is done
2、notify和notifAll的区别
两个概念
锁池EntryList
等待池 WaitSet
标签:public 概念 demo lis one object static 注释 cep
原文地址:https://www.cnblogs.com/linlf03/p/12113185.html