我有 2 个线程 T1 和 T2。 T2 在收到来自 T1 的消息后应该开始工作。 T1 和 T2 均在 main() 中启动。 T1 无法启动 T2。
这是我到目前为止所拥有的:
T1:
//do work1 which should be executed before work2
lock2.notify()
T2:
lock2.wait();
//do work2 which should be executed after work1 ends
问题在于,有时T1先于T2启动,而T2永远得不到T1发送的通知并永远等待。
我可以使用任何现有的并发实用程序来实现此信号发送吗?
谢谢。
最佳答案
两个线程之间需要一些同步机制。下面是我使用 CountDownLatch 来实现此目的的示例。我定义了一个 SyncedThread
类,它获取构造函数中传递的 CountDownLatch
。
在主方法中,我创建了该类的两个实例。首先,thread1
将运行 2 秒,然后向 CountDownLatch 发出信号,然后再进行 3 秒的虚拟 sleep 。
第二个实例 thread2
将等待 CountDownLatch,然后 hibernate 5 秒以模拟工作。
thread2.start()
方法,然后调用 thread1.start()
,延迟 500 毫秒,但是通过使用同步,您将在输出实际上 thread2
正在等待 thread1
。
public class ThreadStarterTest {
public static void main(String[] args) {
final CountDownLatch latch = new CountDownLatch(1);
SyncedThread thread1 = new SyncedThread(latch, "thread 1") {
@Override
public void run() {
try {
System.out.println(getName() + " running");
Thread.sleep(2_000);
latch.countDown();
Thread.sleep(3_000);
System.out.println(getName() + " finished");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
SyncedThread thread2 = new SyncedThread(latch, "thread 2") {
@Override
public void run() {
try {
latch.await();
System.out.println(getName() + " running");
Thread.sleep(5_000);
System.out.println(getName() + " finished");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
try {
thread2.start();
Thread.sleep(500);
thread1.start();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public static class SyncedThread extends Thread {
private final CountDownLatch latch;
public SyncedThread(final CountDownLatch latch, final String name) {
super(name);
this.latch = latch;
}
}
}
关于java - 如何确保一个线程在另一个线程之前启动?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44127483/