147_多线程(线程间通信-生产者消费者JDK5.0升级版)

/*JDK1.5及以上提供了多线程升级解决方案。
将同步Synchronized替换成Lock操作。
将Object中的wait,notify,notifyAll,用Condition对象替换。
该对象可以用lock进行获取。

该实例中实现了本方只唤醒对方的操作。
及生产者只唤醒消费者。
消费者只唤醒生产者。
*/


import java.util.concurrent.locks.*;

class ProducerConsumer{
	public static void main(String[] args){
		Resource r = new Resource();
		Producer pro = new Producer(r);
		Consumer con = new Consumer(r);
		
		Thread t1 = new Thread(pro);
		Thread t2 = new Thread(pro);
		Thread t3 = new Thread(con);
		Thread t4 = new Thread(con);
		
		t1.start();
		t2.start();
		t3.start();
		t4.start();
	}
}

class Resource{
	private String name;
	private int count = 1;
	private boolean flag = false;
	
	private Lock lock = new ReentrantLock();
	
	private Condition conProducer = lock.newCondition();
	private Condition conConsumer = lock.newCondition();
	
	public void set(String name)throws InterruptedException{
		lock.lock();
		try{
			while(flag)
				conProducer.await();
			this.name = name +"--"+count++;
			System.out.println(Thread.currentThread().getName()+
			"-生产者-"+this.name);
			flag = true;
			conConsumer.signal();
		}
		finally{
			lock.unlock();
		}
	}
	
	public void out()throws InterruptedException{
		lock.lock();
		try{
			while(!flag)
				conConsumer.await();
			System.out.println(Thread.currentThread().getName()+
			"-消费者-"+this.name);
			flag = false;
			conProducer.signal();
		}
		finally{
			lock.unlock();
		}
	}
}

class Producer implements Runnable{
	private Resource res;
	
	Producer(Resource res){
		this.res = res;
	}
	public void run(){
		while(true){
			try{
				res.set("+商品+");
			}
			catch(InterruptedException e){
				
			}
			
		}
	}
}

class Consumer implements Runnable{
	private Resource res;
	
	Consumer(Resource res){
		this.res = res;
	}
	public void run(){
		while(true){
			try{
				res.out();
			}
			catch(InterruptedException e){
				
			}
		}
	}
}

猜你喜欢

转载自317324406.iteye.com/blog/2250917