0

I want to stop a thread which does not have loop so like

while(!cancelled) //where cancelled is volatile variable
{
   //
}

cannot be used as I want to execute long running task without loop, how to stop child threads if exception occurs in any of them from parent thread

@Oliver

As mentions in oracle docs

for (int i = 0; i < inputs.length; i++) {
    heavyCrunch(inputs[i]);
    if (Thread.interrupted()) {
        // We've been interrupted: no more crunching.
        return;
    }
}

in above code if() will call only if heavyCrunch(inputs[i]) completed

Hitesh Ghuge
  • 793
  • 2
  • 10
  • 39
  • `Thread.interrupt` should be the way to do that – Sanjeev Jun 18 '16 at 10:48
  • @hitesh, if you are using ExecutorService, have a look at this question : http://stackoverflow.com/questions/37879274/interrupt-all-threads-if-exception-occurs-in-any-of-the-thread-among-the-thread/ – Ravindra babu Jun 18 '16 at 14:38

1 Answers1

0

It looks like you're aiming for a interrupt driven application. You could retain a list of the threads you have spawned and in your exception iterate through the other threads and interrupt them.

https://docs.oracle.com/javase/tutorial/essential/concurrency/interrupt.html

Oliver Hemsted
  • 571
  • 2
  • 13