wait notify 锁机制

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只唤醒线程,不释放锁。下次继续分享。关于如何解决实时释放锁资源的方法。



                

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值