1. 程式人生 > >13,多線程-生產者消費者問題2

13,多線程-生產者消費者問題2

sign post cep pre int all ren test pac

關鍵代碼1

private Lock lock = new ReentrantLock();

private Condition condition_pro = lock.newCondition();

private Condition condition_con = lock.newCondition();

關鍵代碼2

r.getLock().lock();

try{r.getCondition_pro().await();}catch(Exception e){} r.getCondition_con().signalAll(); r.getLock().unlock(); 、

完整代碼:

package songyan;
import java.util.concurrent.locks.*;
 class Res{
     private Lock lock = new ReentrantLock();

     public Lock getLock() {
        return lock;
    }
    public void setLock(Lock lock) {
        this.lock = lock;
    }
    private Condition condition_pro = lock.newCondition();
     
public Condition getCondition_pro() { return condition_pro; } public void setCondition_pro(Condition condition_pro) { this.condition_pro = condition_pro; } public Condition getCondition_con() { return condition_con; } public void setCondition_con(Condition condition_con) {
this.condition_con = condition_con; } private Condition condition_con = lock.newCondition(); private String name; private int id; private boolean flag; public boolean getFlag() { return flag; } public void setFlag(boolean flag) { this.flag=flag; } public String getName() { return name; } public int getId() { return id; } public void setName(String name) { this.name=name; } public void setId(int id) { this.id=id; } } class Pro implements Runnable{ private Res r; public void run() { int x=0; while(true) { r.getLock().lock(); while(r.getFlag()) try{r.getCondition_pro().await();}catch(Exception e){} if(x==0) { r.setName("張三"); r.setId(r.getId()+1); System.out.println(r.getName()+"**生產*****"+r.getId()); } else{ r.setName("zhangsan"); r.setId(r.getId()+1); System.out.println(r.getName()+"**生產*****"+r.getId()); } x=(x+1)%2; r.setFlag(true); r.getCondition_con().signalAll(); r.getLock().unlock(); } } Pro(Res r) { this.r=r; } } class Cons implements Runnable{ private Res r; public void run() { while(true) { r.getLock().lock(); while(!r.getFlag()) try{r.getCondition_con().await();}catch(Exception e){} System.out.println(r.getName()+"***消費者****"+r.getId()); r.setFlag(false); r.getCondition_pro().signalAll(); r.getLock().unlock(); } } Cons(Res r) { this.r=r; } } public class test{ public static void main(String[] args) { Res r= new Res(); Pro p= new Pro(r); Cons c= new Cons(r); Thread t1= new Thread(p); Thread t2= new Thread(c); Thread t3= new Thread(p); Thread t4= new Thread(c); t1.start(); t2.start(); t4.start(); t3.start(); } }

13,多線程-生產者消費者問題2