本帖最后由 艮昕辶 于 2014-5-21 17:16 编辑
- <font color="#ff0000">Lock lock = new ReentrantLock();</font>
- //通过已有的锁获取两组监视器,一组监视生产者,一组监视消费者。
- <font color="#ff0000"> Condition producer_con = lock.newCondition();
- Condition consumer_con = lock.newCondition();</font>
-
- public void set(String name)// t0 t1
- {
- <font color="#ff0000"> lock.lock();</font>
- try
- {
- while(flag)
- try{<font color="#ff0000">producer_con.await();</font>}catch(InterruptedException e){}// t1 t0
-
- this.name = name + count;//烤鸭1 烤鸭2 烤鸭3
- count++;//2 3 4
- System.out.println(Thread.currentThread().getName()+"...生产者5.0..."+this.name);//生产烤鸭1 生产烤鸭2 生产烤鸭3
- flag = true;
- <font color="#ff0000"> consumer_con.signal();</font>
- }
- finally
- {
- <font color="#ff0000"> lock.unlock();</font>
- }
-
- }
- public void out()// t2 t3
- {
- <font color="#ff0000"> lock.lock();</font>
- try
- {
- try{cousumer_con.await();}catch(InterruptedException e){} //t2 t3
- System.out.println(Thread.currentThread().getName()+"...消费者.5.0......."+this.name);//消费烤鸭1
- flag = false;
- <font color="#ff0000">producer_con.signal();</font>
- }
- finally
- {
- <font color="#ff0000"> lock.unlock();</font>
- }
-
- }
复制代码 |