javamultithreadingsleeppausesuspend

Is there a way to pause all threads from the main one in Java?


Basically is that. Lets say I have a program with 6 threads (including the main one). Is there a way to pause/sleep/suspend all the other 5 threads from the main one? lets say by getting their ID then used it to suspend all of them (or by any other method).


Solution

  • This will give you all the threads of the application created so far

    Set<Thread> threadSet = Thread.getAllStackTraces().keySet();
    

    To stop a thread you will have to write your own customized thread class like explained in this example which is using a flag to control the thread execution

    https://www.baeldung.com/java-thread-stop

    While iterating over the set of the threads threadSet set the value of the flag to make it stop