One thread dependent on the other

浪子不回头ぞ 提交于 2019-12-11 18:14:32

问题


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?


回答1:


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
 }
}



回答2:


Use a Future and cancel it when necessary.




回答3:


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)



来源:https://stackoverflow.com/questions/21826369/one-thread-dependent-on-the-other

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!