Object obj = new Object();
new Thread(){
@Override
public void run() {
while(true){
synchronized (obj){
System.out.println("告知老板包子数量和种类");
try {
obj.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("开吃!!!");
System.out.println("----------------");
}
}
}
}.start();
new Thread(){
@Override
public void run() {
while (true){
System.out.println("老板正在做包");
for(int i=0;i<5;i++){
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("。");
}
synchronized (obj){
System.out.println("包子做好了");
obj.notify();
//notifyAll();释放所有线程
}
}
}
}.start();
创建一个锁对象
Object obj = new Object();
创建一个同步代码块
防止两个线程同时运行
先占用cpu运行
synchronized (obj)
暂停运行线程释放cpu,等待notify
obj.wait();
在括号内加入数字,表示即使没有释放,也会自动运行,相当于sleep
运行结果如下:
无限循环运行