java - Thread.sleep 显然不会强制上下文切换

标签 java multithreading concurrency thread-sleep java-threads

主线程创建子线程。父级需要子级完成一些工作,但不是全部,因此父级必须等到子级完成该工作(子级将继续做一些其他工作)。

我想用监视器来实现它,所以我编写了以下代码:

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/

相关文章:

java - 无法打开 ServletContext 资源 [/src/main/resources/security-context.xml]

Python线程,线程不关闭

go - Go 中令人尴尬的并行任务的惯用解决方案是什么?

java - 共享队列 VS Actor 模型

haskell - 带 Warp/WAI 的线程安全状态

java - 如何通过传递搜索字符串在浏览器中显示 pdf 文件,并且需要使用 java 显示第一个包含突出显示的搜索字符串的页面

java - panoramagl 热点将移至下一个全景

java - Android不同屏幕下的ImageButton

java套接字如何从两个不同的线程发送数据

.net - 在 C# 中一次下载多个 HTML