显式锁和条件变量Java Producer Consumer

时间:2016-04-08 18:48:28

标签: java multithreading condition-variable

我正在尝试运行我从http://www.math.uni-hamburg.de/doc/java/tutorial/essential/threads/explicitlocks.html获得的生产者消费者示例,代码如下。当我运行它时,它只运行两次,似乎挂起。代码似乎正在解锁并发出正确的信号,有人知道我错过了什么。

    static Thread t1;
static Thread t2;


public static void main(String[] args){
    Lab2 r1=new Lab2();
    Lab2 r2=new Lab2();


    t1=new Thread(r1, "producer");
    t2= new Thread(r2, "consumer");
    //System.out.println("Adding");

    t1.start();
    t2.start();

}



public int get(int who) {

    aLock.lock();
    System.out.println("locked1");

    try {
        while (available == false) {

            try {
                System.out.println("false avail waiting");

                condVar.await();
                System.out.println("false avail waiting done");

            } catch (InterruptedException e) { }
        }
        available = false;
        System.out.println("Consumer " + who + " got: " +
                            contents);
        condVar.signalAll();
    } finally {
        aLock.unlock();
        return contents;
    }
}

public void put(int who, int value) {


                aLock.lock();
                System.out.println("locked");

try {
    while (available == true) {
        System.out.println("true avail");
        try {
            condVar.await();
        } catch (InterruptedException e) { }
    }
    contents = value;
    available = true;
    System.out.println("Producer " + who + " put: " +contents);
    condVar.signalAll();
    //condVar.signal();
    } finally {
        aLock.unlock();

    }
}


public void run() {
    //System.out.println(Thread.currentThread().getName()+" Thread started");
    int i=0;
    //System.out.println("Adding");

    while(i<10){
        i++;
        //System.out.println(i);
        if (Thread.currentThread().getName().equals("producer")){
        get(2);
        //producer();
        }
        else{
        put(2,1);
        //consumer();
        }
        //break;
    }
}

1 个答案:

答案 0 :(得分:1)

你的问题在这里:

Lab2 r1=new Lab2();
Lab2 r2=new Lab2();

t1=new Thread(r1, "producer");
t2= new Thread(r2, "consumer");

即。你有两个线程执行独立的runnables(r1,r2),但它们应该提供相同的runnable。

将其替换为:

Lab2 r=new Lab2();

t1=new Thread(r, "producer");
t2= new Thread(r, "consumer");