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
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.
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
}
I think you may want to look at the wait() and notify() methods against java.lang.Object
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.
synchronized
block.wait()
on a common object (possibly itself). commonObject.notify()
.Same logic as thread pool. where the threads are in a pool until they are invoked to perform some action submitted to the pool