首页 > 代码库 > 生产者-消费者模式-一对一交替打印

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

 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 }

 

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