您的位置:首页 > 编程语言 > Java开发

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

2016-05-06 14:30 736 查看
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();

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: