本帖最后由 黄连兵 于 2012-6-12 09:57 编辑
毕老师的视频教程多线程中有一个经典例子,使用Lock+Condition来替代Synchronize。
其中的Condition_p 和 Condition_c 是如何跟线程绑定的?使得lock可以把当前线程分成两种情况来管理?
例子中两个生产线程t1,t2,两个消费线程t3 , t4并没有显式地与Condition_p 和 Condition_c绑定,
我们只知道Condition_p结束后会唤醒Condition_c,Condition_c结束后会唤醒Condition_p.
个人的理解是,两类线程通过程序的入口来实现的绑定,Producer的入口是set(),进去后就是Condition_p,而Consumer的入口是out(),进去后就是Condition_c,- <p>package com.practise;
- import java.util.concurrent.locks.*;
- </p><p>
- public class Lock {
- </p><p> /**
- * @param args
- */
- public static void main(String[] args) {
- // TODO Auto-generated method stub</p><p> Resource res=new Resource();
- Thread pro1=new Thread(new Producer(res));
- Thread pro2=new Thread(new Producer(res));
-
- Thread con1=new Thread(new Consumer(res));
- Thread con2=new Thread(new Consumer(res));
- pro1.start();
- pro2.start();
- con1.start();
- con2.start();
- }
- }
- </p><p>
- class Resource{
- private String name;
- private int count=1;
- private boolean flag=false;
-
- private ReentrantLock lock=new ReentrantLock();
- //此处为什么我写成private Lock lock=new ReentrantLock();会报错,这个向上转型有问题么?毕老师的是正常的~!难道又是版本问题?
- </p><p>
- private Condition condition_p=lock.newCondition();
- private Condition condition_c=lock.newCondition();
-
- public void set(String name)throws InterruptedException{
- lock.lock();
- try{
- while(flag)
- condition_p.await();
- this.name=name+"..."+count++;
- System.out.println(Thread.currentThread().toString()+"...producer..."+this.name);
- flag=true;
- condition_c.signal();
- }
- finally{
- lock.unlock();
- }
- }
- public void out()throws InterruptedException{
- lock.lock();
- try{
- while(!flag)
- condition_c.await();
- System.out.println(Thread.currentThread().toString()+"......consumer......"+this.name);
- flag=false;
- condition_p.signal();
- }
- finally{
- lock.unlock();
- }
- }
- }</p><p>class Producer implements Runnable{
- private Resource res;
- Producer(Resource res)
- {
- this.res=res;
- }
- public void run(){
- while(true)
- try {
- res.set("商品");
- } catch (InterruptedException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
- }</p><p>class Consumer implements Runnable{
- private Resource res;
- Consumer(Resource res)
- {
- this.res=res;
- }
- public void run(){
- while(true)
- try {
- res.out();
- } catch (InterruptedException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
- }</p><p> </p>
复制代码 |