Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pause Thread execution

Tags:

java

How to pause execution of some Thread. I have Thread t and I have two buttons, PAUSE and CONTINUE. On pause I need to pause thread execution and on continue to thread start execution from point where stoped before. What to put in listeners?

like image 612
Almira Bojani Avatar asked Feb 25 '23 03:02

Almira Bojani


1 Answers

Threading in Java is cooperative, which means you can not force the thread to stop or pause, instead you signal to the thread what you want and thread (= your logic) does it itself.

Use synchronized, wait() and notify() for that.

  1. Create an atomic flag (e.g. boolean field) in the thread to be stopped. Stoppable thread monitors this flag in the loop. Loop must be inside synchronized block.
  2. When you need to stop the thread (button click) you set this flag.
  3. Thread sees the flag is set and calls wait() on a common object (possibly itself).
  4. When you want to restart the thread, reset the flag and call commonObject.notify().
like image 175
Peter Knego Avatar answered Feb 26 '23 22:02

Peter Knego