Java wait()和死锁

时间:2017-08-30 14:38:55

标签: java multithreading wait notify

我正在测试一个用于多线程应用程序中的通信的类。虽然popadd的简单使用没有问题,但当我尝试检查堆栈是否为空,然后wait,直到有人add是一个元素时,事情就会中断它

我的课程:

public class SynchronizedStack<T>{
private final Stack<T> data;
public SynchronizedStack(){
    this.data = new Stack<>();
}

public T pop(){
    synchronized (this.data) {
        if(this.data.isEmpty())
            return null;
        T object = this.data.pop();
        this.data.notifyAll();
        return object;
    }
}

public void add(T e){
    synchronized (this.data){
        this.data.add(e);
        this.data.notifyAll();
    }
}

public void waitUntilFilled() throws InterruptedException {
    synchronized (this.data){
        while(this.data.isEmpty())
            this.data.wait();
    }
}

我的问题在于waitUntilFilled方法。当它被调用并且堆栈被填满时,没有任何错误,但是当它在空堆栈上被调用时会导致死锁。

我的测试用例:

@Test
public void testWaitUntilFilled(){
    SynchronizedStack<Integer> ss = new SynchronizedStack<>();
    Runnable producer = ()->{
        ss.add(1);
    };

    Runnable consumer = ()->{
        try {
            ss.waitUntilFilled();
        } catch (InterruptedException e) {
            fail(e);
        }
        assertNotNull(ss.pop());
    };

    Thread p = new Thread(producer, "producer");
    Thread c = new Thread(consumer, "consumer");

    c.run();
    p.run();
}

0 个答案:

没有答案
相关问题