package com.study.thread;
import java.util.ArrayList;
import java.util.List;
public class NotifyWaitTest {
private volatile static List<Integer> count = new ArrayList<Integer>();
public static void main(String[] args) {
NotifyWaitTest notifyWaitTest = new NotifyWaitTest();
Object object = new Object();
new Thread(new Runnable() {
@Override
public void run() {
synchronized (object) {
System.out.println("notify is begin.....first.........");
if (notifyWaitTest.count.size() != 5) {
try {
object.wait();
System.out.println("notify is begin..............");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}).start();
new Thread(new Runnable() {
@Override
public void run() {
synchronized (object){
for (int i=0;i<10;i++){
notifyWaitTest.count.add(1);
System.out.println("--------------------i=" + i);
if (notifyWaitTest.count.size()==5){
object.notify();
}
}
}
}
}).start();
}
}
运行结果如下
wait 释放锁, notify 不会释放锁,要等到程序结束,才会释放 获得的 对象锁