我可以使用CountDownLatch控制线程执行的顺序吗? [英] Can I control order of thread execution with CountDownLatch?

查看:248
本文介绍了我可以使用CountDownLatch控制线程执行的顺序吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have task to do. I have to create 4 services A,B,C and D. Each service should have his own thread. A service should only start after all the services that it depends on are started and A service should only stop after all the services that depend on it are stopped. Services should be started and stopped in parallel whenever possible. Services B and C depend on Service A Service D depends on Service B To start service D, service A and B need to be started To stop service A, service B, D and C must be stopped first Service B and C can be started in parallel immediately after A has started. Conversely, they can stop in parallel.

您对如何解决此问题有任何建议吗?我正在尝试过去10天...可以用CountDownLatch或其他方法来做吗?任何建议都是可取的.

Do you have any suggestions how to solve this? I'm trying to do it for last 10 days...Can i do it with CountDownLatch or with something else? Any advice is appreciable.

推荐答案

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

You can use a blocking queue to communicate between the worker threads and the main thread, something like

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

Use similar logic for stopping the threads (use a while(!isCancelled) loop in your services, and have your main thread call cancel() on the services when it's time to stop them).

这篇关于我可以使用CountDownLatch控制线程执行的顺序吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆