简体   繁体   English

如何暂停线程执行

[英]How to pause Thread execution

How to pause execution of some Thread. 如何暂停某些Thread的执行。 I have Thread t and I have two buttons, PAUSE and CONTINUE. 我有Thread t,我有两个按钮,PAUSE和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? 把什么放在听众中?

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. Java中的线程是合作的,这意味着你不能强制线程停止或暂停,而是向线程发出你想要的信号和线程(=你的逻辑)自己做的信号。

Use synchronized, wait() and notify() for that. 使用synchronized,wait()和notify()。

  1. Create an atomic flag (eg boolean field) in the thread to be stopped. 在要停止的线程中创建一个原子标志(例如布尔字段)。 Stoppable thread monitors this flag in the loop. Stoppable线程在循环中监视此标志。 Loop must be inside synchronized block. 循环必须在synchronized块内。
  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). 线程看到标志已设置并在公共对象(可能是自身)上调用wait() )。
  4. When you want to restart the thread, reset the flag and call commonObject.notify() . 如果要重新启动线程,请重置标志并调用commonObject.notify()

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
 }

我想你可能想看看针对java.lang.Object的wait()和notify()方法

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. 如果它不是作业,那么可能还有其他解决方案。

Same logic as thread pool. 与线程池相同的逻辑。 where the threads are in a pool until they are invoked to perform some action submitted to the pool 线程在池中的位置,直到它们被调用以执行提交到池的某些操作

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM