How to pause Thread execution

前端 未结 5 1202
耶瑟儿~
耶瑟儿~ 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:41

    There is a wait and await that you can call. Await sounds closer to what you are looking for. Why do you need to pause the execution of some thread? If it for something other than homework there may be other solutions.

    0 讨论(0)
  • 2021-01-03 09:41

    You can try this:

    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 讨论(0)
  • 2021-01-03 09:43

    I think you may want to look at the wait() and notify() methods against java.lang.Object

    0 讨论(0)
  • 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().
    0 讨论(0)
  • 2021-01-03 09:50

    Same logic as thread pool. where the threads are in a pool until they are invoked to perform some action submitted to the pool

    0 讨论(0)
提交回复
热议问题