![](/img/trans.png)
[英]How can a CountDownLatch object be passed to the constructor of a Thread?
[英]Can I control order of thread execution with CountDownLatch?
我有任务要做。 我必须创建4个服务A,B,C和D。每个服务应具有自己的线程。 服务应仅在其依赖的所有服务启动后启动,服务应仅在依赖它的所有服务停止后启动。 服务应尽可能并行启动和停止。 服务B和C取决于服务A服务D取决于服务B要启动服务D,需要启动服务A和B要停止服务A,必须先停止服务B,D和C,然后才能在其中启动服务B和C。 A开始后立即并联。 相反,它们可以并行停止。
您对如何解决这个有什么建议吗? 我正在尝试过去10天...可以用CountDownLatch或其他方法来做吗? 任何建议都是可取的。
您可以使用阻塞队列在工作线程和主线程之间进行通信,例如
public static void main(String[] args) {
BlockingQueue<String> queue = new LinkedBlockingQueue<>();
Thread t1 = new Thread(new A(queue));
t1.start();
if(queue.take().equals("Started A")) {
Thread t2 = new Thread(new B(queue));
t2.start();
Thread t3 = new Thread(new C());
t3.start();
}
if(queue.take().equals("Started B")) {
Thread t4 = new Thread(new D());
t4.start();
}
}
public class A implements Runnable {
private BlockingQueue queue;
private volatile boolean isCancelled = false;
public A(BlockingQueue queue) {
this.queue = queue;
}
public void cancel() {
isCancelled = true;
}
public void run() {
// initialization code
queue.offer("Started A");
while(!isCancelled) {
...
}
queue.offer("Stopped A");
}
}
使用类似的逻辑来停止线程(在服务中使用while(!isCancelled)
循环,并在需要停止服务时对服务调用主线程cancel()
)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.