How to pause a topic

How to pause the execution of some thread. I have Thread t, and I have two buttons: PAUSE and CONTINUE. In a pause, I need to pause the thread and continue to start the thread from the point where it was stopped earlier. What to add listeners?

+4
source share
5 answers

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() .
+8
source

I think you can see the wait () and notify () methods in java.lang.Object

0
source

Waiting and waiting for you to call. Waiting for sound is closer to what you are looking for. Why do you need to pause a thread? If for something other than homework, there may be other solutions.

0
source

The same logic as the thread pool. where the threads are in the pool until they are called to perform some actions sent to the pool

0
source

You can try the following:

 private boolean isPaused = false; public synchronized void pause(){ isPaused = true; } public synchronized void play(){ isPaused = false; notyfyAll(); } public synchronized void look(){ while(isPaused) wait(); } public void run(){ while(true){ look(); //your code } 
0
source

All Articles