gpt4 book ai didi

java - 如何让线程等待

转载 作者:行者123 更新时间:2023-11-30 07:10:18 26 4
gpt4 key购买 nike

我想等到线程进入等待状态。我一直在尝试使用 join(见下文),但它不起作用。如何实现这一目标?

public Test() {
System.out.print("Started");
Thread thread = new Thread(() -> {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (Test.class) {
try {
Test.class.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
thread.start();

try {
thread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.print("Done");
}

完成永远不会被打印。

最佳答案

你的主线程不会超越join(),因为第二个线程永远不会结束。第二个线程永远不会结束,因为它正在等待 Test.class 的通知,但没有人通知它。

如果您希望主线程在第二个线程到达 Test.class.wait(); 行时继续执行,则需要引入另一个监视器来进行此同步。主线程必须在此监视器上等待,第二个线程必须在准备好切换到等待状态时通知它:

System.out.println("Started");
final Object monitor = new Object();
Thread thread = new Thread(() -> {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Finished");
synchronized (monitor) {
monitor.notify(); // Notify the main thread
}
synchronized (Test.class) {
try {
Test.class.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
thread.start();

synchronized (monitor) {
try {
monitor.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("Done");

这段代码可以工作,尽管看起来有点难看。它还会留下一个挂起的线程,阻止您的程序正常终止。如果您希望此线程完成,您需要有人调用 Test.class.notify()

从您的问题中尚不清楚您总体上想要实现什么目标。如果您想生成一个线程并等待它完成,则不需要这些 wait()notify(),只需使用 join( ):

System.out.println("Started");
Thread thread = new Thread(() -> {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Finished");
});
thread.start();

try {
thread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Done");

还有一件事:在构造函数中创建和启动线程是一个非常糟糕的主意。为此,请使用单独的方法(例如 initialize())。

关于java - 如何让线程等待,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39329202/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com