import java.util.ArrayList;
import java.util.List;
import java.util.logging.Logger;
/**
*
*测试wait和notify对于锁的持有
*
*/
public class WaitAndNotify {
//单个实例的共享容器
private volatile List<Object> list= new ArrayList<Object>();
//锁
private Object lock = new Object();
//生产者
private static class Produce implements Runnable{
private Object lock;
private List<Object> list;
private Integer size;
public Produce(Object lock,List<Object> list,Integer size){
this.lock = lock;
this.list = list;
this.size = size;
}
public void run() {
try {
synchronized (lock) {
for(int i = 0; i <size; i++){
list.add("it is a item!");
System.out.println("currentThread:" + Thread.currentThread().getName() + "add one item..");
Thread.sleep(500);
if(list.size() == 5){
System.out.println("gived the notice");
lock.notify();
}
}
}
} catch (InterruptedException e) {
Logger.getGlobal().log(null, "produce sleep error.");
}
}
}
//消费者
private static class Consumer implements Runnable{
private Object lock;
private Integer size;
public Consumer(Object lock,Integer size){
this.lock = lock;
this.size = size;
}
public void run() {
try {
synchronized (lock) {
if(size != 5){
lock.wait();
}
System.out.println("currentThread:" + Thread.currentThread().getName() + "收到通知线程停止..");
throw new RuntimeException();
}
} catch (InterruptedException e) {
Logger.getGlobal().log(null, "consumer sleep error.");
}
}
}
public void produceStart() throws Exception{
//生产者
Thread produce = new Thread(new Produce(lock,list,10));
produce.start();
}
public void consumerStart() throws Exception{
//消费者
Thread consumer = new Thread(new Consumer(lock,list.size()));
consumer.start();
}
public static void main(String[] args) {
try {
WaitAndNotify waitAndNotify = new WaitAndNotify();
waitAndNotify.consumerStart();
waitAndNotify.produceStart();
} catch (Exception e) {
Logger.getGlobal().log(null, "main error.");
}
}
}
</pre><pre name="code" class="html">
</pre><pre name="code" class="html"> 总结:
1.wait 释放锁 。2.notify只唤醒线程,不释放锁。下次继续分享。关于如何解决实时释放锁资源的方法。