user3239652
user3239652

Reputation: 785

One thread dependent on the other

If 4 threads are running,and want that if t1 thread completes its instruction,and terminate,and want that t2 should also terminate after t1 terminates,even its instruction is not fully completed,while t3 and t4 are still running,that is it should only depend on t2,neither on t3 nor on t4.

Someone suggested me make t2 daemon,but that would make t2 dependent on t3 as well as on t4.Any one could help me out with an example how to do that?

Upvotes: 0

Views: 1579

Answers (3)

ratchet freak
ratchet freak

Reputation: 48216

blind destruction of threads is a dangerous thing

in java the best thing you can do is interrupt() t2 and let it bubble up (with manual checks as needed) so t2 can clean up after itself

for example in a loop you can do:

if(Thread.interrupted())throw new InterruptedException();

regularly in t2 (or a custom TimeoutException if that is your style to avoid the checked InterruptedException)

Upvotes: 1

Subhrajyoti Majumder
Subhrajyoti Majumder

Reputation: 41220

you can implement using CountDownLatch.

It is a synchronization aid that allows one or more threads to wait until a set of operations being performed in other threads completes.A CountDownLatch is a versatile synchronizati on tool and can be used for a number of purposes. A CountDownLatch initialized with a count of one serves as a simple on/off latch, or gate: all threads invoking await wait at the gate until it is opened by a thread invoking countDown(). A CountDownLatch initialized to N can be used to make one thread wait until N threads have completed some action, or some action has been completed N times.

Code snippet -

CountDownLatch doneSignal = new CountDownLatch(1);
// Share the same object between two thread
Thread T1{
 public void run(){ 
  doneSignal.await(); //T1 will wait untill T2 finshed
  ...
 }
}
...
Thread T2{
 public void run(){ 
  ...
  doneSignal.countDown(); // sending signal that T2 is over
 }
}

Upvotes: 2

Dariusz
Dariusz

Reputation: 22271

Use a Future and cancel it when necessary.

Upvotes: 1

Related Questions