使用Barrier来控制线程同步示例
可能的输出:
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; }
}
}
相关文章
浅谈C#中ToString()和Convert.ToString()的区别
本文介绍了ToString()和Convert.ToString()的使用方法,他们之间的区别,以及从object到string的转换方法,希望对学习C#编程的你有所帮助2016-11-11使用MSScriptControl 在 C# 中读取json数据的方法
下面小编就为大家带来一篇使用MSScriptControl 在 C# 中读取json数据的方法。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过来看看吧2017-01-01
最新评论