主线程创建子线程。父级需要子级完成一些工作,但不是全部,因此父级必须等到子级完成该工作(子级将继续做一些其他工作)。
我想用监视器来实现它,所以我编写了以下代码:
public class WaitChildThreadMonitor {
public static final int TOTAL_COUNT_AMOUNT = 1_000;
static int count = 0;
class Child implements Runnable {
@Override
public void run() {
work();
}
public synchronized void work() {
letParentWaitForThis();
for (int i = 0; i < TOTAL_COUNT_AMOUNT; i++)
++WaitChildThreadMonitor.count;
this.notifyAll();
// More child work that parent doesn't need right now
// ...
for (int i = 0; i < TOTAL_COUNT_AMOUNT; i++)
++WaitChildThreadMonitor.count;
}
private void letParentWaitForThis() {
try {
Thread.sleep(100);
} catch (InterruptedException e) {}
}
public synchronized void waitForWork() throws InterruptedException {
this.wait();
}
}
void main() throws InterruptedException {
Child child = new Child();
Thread childThread = new Thread(child);
// If the next two methods doesn't execute atomically,
// parent execution gets blocked forever
childThread.start();
child.waitForWork();
System.out.printf("Count value is %d\n", WaitChildThreadMonitor.count);
childThread.join();
}
public static void main(String[] args) throws InterruptedException {
(new WaitChildThreadMonitor()).main();
}
}
问题是,如果子进程在完成主要工作后,在父进程在“child.waitForWork()”中执行“this.wait()”之前执行“this.notifyAll()”,则父进程将不会收到通知,并且会永远被封锁。
我试图解决这个问题,在 child 使用 Thread.sleep() 方法开始工作之前强制进行上下文切换。它似乎没有按预期工作。
有 sleep 和没有 sleep ,有时 parent 会被阻止并且程序永远不会结束,有时会正确结束(我猜是因为 parent 在 child 通知之前等待)。
我该如何解决这个问题?
提前致谢!
最佳答案
如果您要等待的事情已经发生,则不得调用wait
。这就是调用 wait
的方法是同步
的原因——这样您就可以检查表示您正在等待的事情的共享状态。
关于java - Thread.sleep 显然不会强制上下文切换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34601339/