0

I have written a java code in which there are number of threads running, and threads are created using SwingWorker class, now I want to terminate all the threads at once. Is there any way to terminate all the threads running?

Luiggi Mendoza
  • 85,076
  • 16
  • 154
  • 332
  • Not unless you have some flag which all of those are monitoring – MadProgrammer Aug 23 '14 at 21:08
  • By default, the threads should terminate if they are idle for 1 second. Can you elaborate what the problem is? – Marco13 Aug 23 '14 at 21:16
  • @Marco13 So, if I put a while(true) loop in a thread, whose only command within that loops is Thread.sleep(2000);, you're saying that the thread will terminate? – MadProgrammer Aug 23 '14 at 22:04
  • @MadProgrammer These threads would not be idle, according to the meaning of "idle" that is used in the `ThreadPoolExecutor` (which roughly is: They did not process any `Runnable` for a while) – Marco13 Aug 23 '14 at 23:07
  • @Marco13 Well, then you're assuming what the OP is doing, they've made no mention of Executors (and yes, I'm aware that SwingWorker is backed by one, but that's not what the OP is talking about) – MadProgrammer Aug 23 '14 at 23:26
  • @MadProgrammer The question obviously lacks details (that's why I asked for more). If the intention is to cancel/interrupt *running* background threads, this will be difficult (as long as simply calling `cancel(true)` on all workers did not suffice). – Marco13 Aug 23 '14 at 23:43

1 Answers1

1

The better way is to create some list of threads created.

Something like this one:

List<Thread> myThreads = new ArrayList<Thread>();

So you keep adding the list the threads you are creating:

myThreads.add(aThread);

so whenever you want to terminate the threads at once, you just loop over your list and terminate all.