一个线程依赖于另一个 [英] One thread dependent on the other

查看:136
本文介绍了一个线程依赖于另一个的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果4个线程正在运行,并且希望t1线程完成其指令并终止,并且希望t2在t1终止后也应该终止,即使其指令没有完全完成,而t3和t4仍在运行,则

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.

有人建议我创建t2守护程序,但这将使t2既依赖于t3又依赖于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?

推荐答案

您可以使用 CountDownLatch

you can implement using CountDownLatch.


它是一种同步辅助工具,它允许一个或多个线程等待
,直到在另一个线程中执行一组操作为止线程完成。CountDownLatch是一种通用的同步工具,可以用于多种目的。初始化为CountDownLatch
的计数用作简单的on / off锁存器或
门:所有调用await的线程在门处等待,直到被countCount()的线程打开
为止。 )。初始化为N
的CountDownLatch可用于使一个线程等待,直到N个线程完成
某项操作或某项操作已完成N次。

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.

代码段-

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

这篇关于一个线程依赖于另一个的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆