时间:2021-05-19
可能的输出:
复制代码 代码如下:
Working on Thread A
Working on Thread B
Thread B will sleep for 10 seconds.
Thread A will sleep for 847 seconds.
Working on Thread C
Thread C will sleep for 26 seconds.
Working on Thread D
Thread D will sleep for 351 seconds.
Working on Thread E
Thread E will sleep for 249 seconds.
All jobs have been done.
代码:
复制代码 代码如下:
using System;
using System.Threading;
class BarrierDemo
{
static Barrier _barrier = new Barrier (5, barrier => {
Console.WriteLine();
Console.WriteLine("All jobs have been done.");
});
static void Main()
{
Random r = new Random();
new Thread(Work).Start(new MyThreadArgs { ThreadId = "A",
WaitTimeCount = r.Next(1000) });
new Thread(Work).Start(new MyThreadArgs {ThreadId = "B",
WaitTimeCount = r.Next(1000) });
new Thread(Work).Start(new MyThreadArgs {ThreadId = "C",
WaitTimeCount = r.Next(1000) });
new Thread(Work).Start(new MyThreadArgs {ThreadId = "D",
WaitTimeCount = r.Next(1000) });
new Thread(Work).Start(new MyThreadArgs {ThreadId = "E",
WaitTimeCount = r.Next(1000) });
}
static void Work(object obj)
{
MyThreadArgs args = (MyThreadArgs) obj;
Console.WriteLine("Working on Thread " + args.ThreadId);
Console.WriteLine("Thread " + args.ThreadId +
" will sleep for " + args.WaitTimeCount + " seconds.");
Thread.Sleep(waitTime);
_barrier.SignalAndWait();
}
class MyThreadArgs
{
public string ThreadId { get; set; }
public int WaitTimeCount { get; set; }
}
}
声明:本页内容来源网络,仅供用户参考;我单位不保证亦不表示资料全面及准确无误,也不保证亦不表示这些资料为最新信息,如因任何原因,本网内容或者用户因倚赖本网内容造成任何损失或损害,我单位将不会负任何法律责任。如涉及版权问题,请提交至online#300.cn邮箱联系删除。
java中控制线程通信的方法1.传统的方式:利用synchronized关键字来保证同步,结合wait(),notify(),notifyAll()控制线程通信
本文实例讲述了Java使用Condition控制线程通信的方法。分享给大家供大家参考,具体如下:一点睛当使用Lock对象来保证同步时,Java提供了一个Cond
Android项目中的一个需求:通过线程读取文件内容,并且可以控制线程的开始、暂停、继续,来控制读文件。在此记录下。直接在主线程中,通过wait、notify、
当线程在系统内运行时,线程的调度具有一定的透明性,程序通常无法准确控制线程的轮换执行,但Java也提供了一些机制来保证线程协调运行。传统的线程通信假设现在系统中
3个线程,线程1输出A,线程2输出B,线程3输出C,让这个3个线程循环有序地输出ABCABC…看到这个题目,感觉很有意思,问题的本质是在多线程执行环境,控制线程