Can I control order of thread execution with CountDownLatch?

烈酒焚心 提交于 2019-12-13 19:49:59

问题


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.

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.


回答1:


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");
    }
}

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



来源:https://stackoverflow.com/questions/17093432/can-i-control-order-of-thread-execution-with-countdownlatch

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!