并发 - 为什么此函数中的最后一条指令永远不会执行?

时间:2011-11-24 16:07:55

标签: java concurrency

我有这段代码:

private void doSomething() throws InterruptedException {
    WorkerThread w= new WorkerThread(this);
    w.start();
    synchronized (synchObj) {
        while (!isDone) {
            synchObj.wait();
        }
    }
    System.out.println("End");
}

notifyAll()实例完成时,调用类实现一个在synchObj上调用WorkerThread的方法。除了最终调用System.out.println("End");之外从未调用过,所有内容都可以正常工作。那是为什么?

编辑:以下是其余代码:

public class App implements Notifee {
    private boolean isDone = false;
    private final Object synchObj = new Object();
    /**
     * @param args
     */
    public static void main(String[] args) {
        App app = new App();
        for (int i = 0; i < 5; i++) {
            try {
                app.doSomething();
            } catch (InterruptedException e) {
                System.err.println("Didn't even start");
                e.printStackTrace();
            }
        }
    }       

    private void doSomething() throws InterruptedException {
        WorkerThread w= new WorkerThread(this);
        w.start();
        synchronized (synchObj) {
            while (!isDone) {
                synchObj.wait();
            }
        }
            System.out.println("End");
    }

    @Override
    public void letMeKnow() {
        synchronized (synchObj) {
            synchObj.notifyAll();
        }
    }       
}

public class WorkerThread extends Thread {
    private Notifee n;
    public WorkerThread(Notifee n){
        this.n = n;
    }

    @Override
    public void run() {
        try {
            Thread.sleep(500);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        n.letMeKnow();
    }
}

1 个答案:

答案 0 :(得分:1)

您永远不会将isDone设置为true。你也应该把它volatile。您可能应该添加:

@Override
public void letMeKnow() {
    isDone = true;
    synchronized (synchObj) {
        synchObj.notifyAll();
    }
} 

编辑:如果您想等待工作线程完成通话:

w.join();