【问题标题】:Can I control order of thread execution with CountDownLatch?我可以使用 CountDownLatch 控制线程执行的顺序吗?
【发布时间】:2013-06-13 17:30:40
【问题描述】:

我有任务要做。我必须创建 4 个服务 A、B、C 和 D。每个服务都应该有自己的线程。一个服务应该只有在它所依赖的所有服务都启动并且 一个服务应该只在依赖它的所有服务都停止后才停止。服务应尽可能并行启动和停止。 服务 B 和 C 依赖于服务 A 服务 D 依赖于服务 B 要启动服务D,需要启动服务A和B 要停止服务 A,必须先停止服务 B、D 和 C 服务 B 和 C 可以在 A 启动后立即并行启动。相反,它们可以并行停止。

您对如何解决这个问题有什么建议吗?我试图在过去 10 天里这样做......我可以用 CountDownLatch 还是用其他东西来做?任何建议都是可观的。

【问题讨论】:

标签: java multithreading countdownlatch


【解决方案1】:

您可以使用阻塞队列在工作线程和主线程之间进行通信,例如

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())。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-06-08
    • 2012-09-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-23
    相关资源
    最近更新 更多