Threading in Java is collaborative, which means you cannot force a thread to stop or pause, instead you point to the thread what you want, and the thread (= your logic) does it yourself.
Use synchronized, wait () and notify () for this.
- Create an atomic flag (for example, a boolean field) in the thread you want to stop. Stoppable thread controls this flag in a loop. The loop should be inside the
synchronized block. - When you need to stop the stream (click the button), you will set this flag.
- Thread sees that the flag is set and calls
wait() on the shared object (possibly by itself). - If you want to restart the thread, reset the flag and call
commonObject.notify() .
source share