码迷,mamicode.com
首页 > 编程语言 > 详细

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

时间:2016-05-07 07:28:48      阅读:176      评论:0      收藏:0      [点我收藏+]

标签:

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();
		
	}
	
}

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

标签:

原文地址:http://blog.csdn.net/smuedward/article/details/51331415

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!