I have some struggle with threads in Java, I have three threads – thread1, thread2, and thread3. Those are doing some task when it started, I want to stop these two threads by thread1. I put thread1 for sleep(500), then I stop the both threads, but the process of two threads are still running. Do you have any idea how to do this?
I have some struggle with threads in Java, I have three threads – thread1,
Share
How’re you attempting to stop them?
Thread.stop? Be warned that this method is deprecated.Instead, look into using some sort of flag for thread 1 to communicate to thread 2 and 3 that they should stop. In fact, you could probably use interrupts.
Below, Thread.interrupt is used to implement the coordination.
Alternatively, you could also use a
volatile boolean(or AtomicBoolean) as means of communicating.Atomic access provided by
volatileandjava.util.concurrent.atomic.*allow you to ensure mutation of the flag is seen by the subject threads.Similarly, you could opt to, rather than use
AtomicBoolean, use a field such as:Better yet, if you take advantage of ExecutorServices, you can also program similar code as follows:
This takes advantage of the fact that ThreadPoolExecutor.shutdownNow interrupts its worker threads in an attempt to signal shutdown.
Running any example, the output should be something to the effect of:
Note the last two lines can come in either order.