手机
当前位置:查字典教程网 >编程开发 >C#教程 >使用Barrier来控制线程同步示例
使用Barrier来控制线程同步示例
摘要:可能的输出:复制代码代码如下:WorkingonThreadAWorkingonThreadBThreadBwillsleepfor10se...

可能的输出:

复制代码 代码如下:

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

}

}

【使用Barrier来控制线程同步示例】相关文章:

C#由当前日期计算相应的周一和周日的实例代码

使用异步方式调用同步方法(实例详解)

C#中使用IrisSkin2.dll美化WinForm程序界面的方法

用C#实现启动另一程序的方法实例

通过C#调用cmd来修改服务启动类型

深入多线程之:用Wait与Pulse模拟一些同步构造的应用详解

C#利用子线程刷新主线程分享教程

C#控制台带参数程序源码编写实例讲解

c#中返回文章发表的时间差的示例

c#.net多线程编程教学——线程同步

精品推荐
分类导航