How best to stop the child thread (Thread and Runnable) indefinitely from the main thread and then resume it?

  • Doraemon, if the answer satisfies you, please accept it (tick next to the answer) - Nick Volynkin

3 answers 3

Do not use the Thread.suspend() and Thread.resume() methods. This is best done using wait() / notify() .

Update

You cannot “suspend” someone else's stream. Threads must cooperate for this. The easiest method is probably to use an ordinary Lock .

Here is an example :

 import java.time.*; import java.util.concurrent.locks.*; class Test { static Lock lock = new ReentrantLock(); public static void main (String[] args) throws java.lang.Exception { Thread worker = new Thread(() -> { try { for (int i = 0; i < 20; i++) { Thread.sleep(20); // если lock взят, мы будет ждать здесь // если нет, мы его берём и тут же отпускаем lock.lock(); lock.unlock(); System.out.println(LocalTime.now()); } } catch (InterruptedException ex) { } }); worker.start(); Thread.sleep(100); System.out.println("Locking..."); lock.lock(); // теперь lock.lock() в другом потоке будет ждать Thread.sleep(500); lock.unlock(); // в теперь не будет System.out.println("Unlocked"); worker.join(); } } 

A couple of lock.lock(); lock.unlock(); lock.lock(); lock.unlock(); need to be placed in those places where the workflow will have to check whether it is not necessary to pause. This is the “collaboration” - the thread itself calls a possibly blocking code in those places where it wants to check if it needs to pause.

  • Can I also give an example to solve a specific problem? - Doraemon
  • one
    @Doraemon: neither do you have a specific task description. - Nick Volynkin

Alternatively, you can do something like this:

 class ChildrenThread extends Thread { private volatile boolean play = true; @Override public void run() { int i = 0; while (!isInterrupted()) { checkPause(); System.out.println(i++); } } public synchronized void play() { play = true; notify(); } public void pause() { play = false; } private synchronized void checkPause() { while (!play) { try { wait(); } catch (InterruptedException ex) { interrupt(); play = true; } } } } 

Example of use:

 public static void main(String[] args) throws InterruptedException { ChildrenThread th = new ChildrenThread(); th.start(); Thread.sleep(100); th.pause(); Thread.sleep(5000); th.play(); Thread.sleep(50); th.pause(); Thread.sleep(10000); th.play(); th.interrupt(); }