Nans
Nans

Reputation: 156

Close all threads except main one

I would like to close all threads that are running (if there are) when my main method is called.

public static void main(String[] args) throws Exception {
  // Close all thread except current one
  ...
  // Remaining of my program
}

Upvotes: 0

Views: 4834

Answers (4)

Nans
Nans

Reputation: 156

This is how I fixed my problem. First, I interrupt the thread that can be itself interrupted :

Thread.currentThread().interrupt();

In main class (or thread), I detect that my previous thread is not alive anymore and then close the last living thread :

Thread trx = new Thread(clTh);
Thread ttx = new Thread(csTh);

trx.start();
ttx.start();
while(trx.isAlive()) {
    Thread.currentThread().sleep(1000);
}

while(ttx.isAlive()) {
    ttx.interrupt();
    Thread.currentThread().sleep(1000);
}

Then in my second thread, that was waiting for a in.readLine(), I handle it that way, testing in.ready().

Upvotes: 0

stepanian
stepanian

Reputation: 11433

The direct answer to your question is to call getThreadGroup on the current thread to get the thread to which the current thread belongs and then enumerate over the other threads and then call interrupt on each one.

The real answer is you should NEVER do this for the reasons specified in the answer provided by Tomasz.

Upvotes: 1

Alexeyy Alexeyy
Alexeyy Alexeyy

Reputation: 39

If some of your threads are performing blocking operation (i.e. don't react to Thread#interrupt()), then it's impossible to close them before the operation is complete, short of killing the JVM. Sorry.

Upvotes: 1

Tomasz Nurkiewicz
Tomasz Nurkiewicz

Reputation: 340903

First of all, are you aware that there are some threads in the JVM that are started automatically and you should never mess around with them? These include Finalizer thread, various JMX threads, Swing's EDT, Reference Handler, etc.

Secondly, are you aware that you cannot just stop a thread in Java safely? You can only ask it gently to stop.

If you are aware of the above, try iterating over all threads in the JVM (see: Get a List of all Threads currently running in Java) and call interrupt() on each of them excluding your main thread. Please do not use stop() as this may lead to very nasty problems like deadlocks.

Upvotes: 8

Related Questions