码迷,mamicode.com
首页 > 其他好文 > 详细

生产者-消费者模式-一对一交替打印

时间:2016-12-11 13:07:54      阅读:273      评论:0      收藏:0      [点我收藏+]

标签:tar   str   port   操作   start   while   catch   util   ctc   

 1 package test5;
 2 
 3 import java.util.concurrent.locks.Condition;
 4 import java.util.concurrent.locks.ReentrantLock;
 5 
 6 public class ProductConsume {
 7 
 8     ReentrantLock lock=new ReentrantLock();
 9     Condition condition = lock.newCondition();
10     private boolean empty=true;
11     private int p=0;
12     
13     public void proDuct(){
14         lock.lock();
15         try {
16             while(empty==false){
17                 condition.await();
18             }
19             System.out.println("开始生产了*");
20             empty=false;
21             condition.signal();
22         } catch (Exception e) {
23             e.printStackTrace();
24         }finally{
25             lock.unlock();
26         }
27     }
28     public void conSume(){
29         lock.lock();
30         try {
31             while(empty==true){
32                 condition.await();
33             }
34             System.out.println("开始消费了0");
35             empty=true;
36             condition.signal();
37         } catch (Exception e) {
38             e.printStackTrace();
39         }finally{
40             lock.unlock();
41         }
42     }
43 }

两线程进行操作:

package test5;

public class Thread1 extends Thread{

    private ProductConsume pc;
    public Thread1(ProductConsume pc){
        this.pc=pc;
    }
    @Override
    public void run(){
            pc.proDuct();
    }
}
 1 package test5;
 2 
 3 public class Thread2 extends Thread{
 4 
 5     private ProductConsume pc;
 6     public Thread2(ProductConsume pc){
 7         this.pc=pc;
 8     }
 9     @Override
10     public void run(){
11             pc.conSume();
12     }
13 }

 

 1 package test5;
 2 
 3 public class Run {
 4 
 5     public static void main(String[] args) {
 6         ProductConsume pc=new ProductConsume();
 7         
 8             for(int i=0;i<1000000;i++){
 9                 Thread1 t1=new Thread1(pc);
10                 Thread2 t2=new Thread2(pc);
11                 t1.start();
12                 t2.start();
13             }
14     }
15 }

 

生产者-消费者模式-一对一交替打印

标签:tar   str   port   操作   start   while   catch   util   ctc   

原文地址:http://www.cnblogs.com/noaman/p/6159255.html

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