How to pause Thread execution

前端 未结 5 1201
耶瑟儿~
耶瑟儿~ 2021-01-03 09:09

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

5条回答
  •  隐瞒了意图╮
    2021-01-03 09:45

    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().

提交回复
热议问题