[英]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()。
synchronized
block. synchronized
块内。 wait()
on a common object (possibly itself). wait()
)。 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.