How do I implement the following: the main thread needs to wait for one thread to be running, and then notify that thread to stop

Viewed 48

I need to check if a thread has started, then tell that thread to stop. Is this right or is there a better way?

Main unit test:

CountDownLatch runningTrigger = new CountDownLatch(1);
CountDownLatch stopTrigger = new CountDownLatch(1);
Thread t = new Thread(new Worker(runLatch, stopLatch));
t.start();
runLatch.await();
// do some validation now that we know the thread has started
stopLatch.countDown(); //notify the waiting thread that it can end and die
class Worker implements Runnable() {

    CountDownLatch runningTrigger;
    CoutnDownLatch stopTrigger;

    Worker(CountDownLatch runningTrigger, CountdownLatch stopTrigger) {
        this.runningTrigger = ...
        ...
    }

    void run() {
        try {
            runningTrigger.countDown();
            stopTrigger.await();
        } catch (Interrupted ... ) { do nothing }
    }

}
0 Answers
Related