java线程通讯——使用Lock和Condition代替synchronized 和 wait, notify notifyAll()

Lock 实现提供了比使用 synchronized 方法和语句可获得的更广泛的锁定操作。

此实现允许更灵活的结构,可以具有差别很大的属性,可以支持多个相关的 Condition 对象。


使用生产者和消费者为例!!!

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**

 * 使用Lock和Condition代替
 * synchronized 和 wait, notify notifyAll();

 */
class Resource2{
	private String product;
	private int count = 1;
	private boolean flag= false;
	
	private Lock lock = new ReentrantLock();
	
	Condition condition_pro = lock.newCondition(); //鎖創建的生產者condition對象!!
	Condition condition_con = lock.newCondition(); //鎖創建的消費者condition對象!!
	
	
	public void produce(String product) throws InterruptedException{
		lock.lock();
		try {
		while(flag){
			
				condition_pro.await();
		}
			
			this.product = product+"----"+ count++;
			System.out.println(Thread.currentThread().getName()+"————生產了————"+this.product);
			flag= true;
			condition_con.signal();  //喚醒消費者對象!!!
		}finally{
			lock.unlock();
		}
	}
	
	public  void consume() throws InterruptedException{
	
		lock.lock();
		try {
		while(!flag){
			
				condition_con.await();
		}
			
			System.out.println(Thread.currentThread().getName()+"————消費了————"+this.product);
			flag= false;
			condition_pro.signal(); //喚起生產者對象!!!
		}finally{
			lock.unlock();
		}
	}
	
}

class Producer2 implements Runnable{
	private Resource2 res;
	
	public Producer2(Resource2 res){
		this.res= res;
	}
	@Override
	public void run() {
		while(true){
		try {
			res.produce("Iphone 7");
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		}
	}
	
}
class Consumer2 implements Runnable{
	private Resource2 res;
	
	public Consumer2(Resource2 res){
		this.res= res;
	}
	@Override
	public void run() {
		while(true){
		try {
			res.consume();
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		}
	}
	
}




public class ProducerComsumer2 {
	
	public static void main(String[] args) {
		
		Resource2 res = new Resource2();
		
		Producer2 pro = new Producer2(res);
		Consumer2 con = new Consumer2(res);
		
		Thread t1 = new Thread(pro,"生產者1");
		Thread t2 = new Thread(pro,"生產者2");
		Thread t3 = new Thread(con,"消費者1");
		Thread t4 = new Thread(con,"消費者2");
		
		t1.start();
		t2.start();
		t3.start();
		t4.start();
		//new Thread(new Producer(res)).start();
		//new Thread(new Consumer(res)).start();
		
	}
	
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值