欢迎来到代码驿站!

.NET代码

当前位置:首页 > 软件编程 > .NET代码

使用Barrier来控制线程同步示例

时间:2022-01-29 09:56:48|栏目:.NET代码|点击:

可能的输出:

复制代码 代码如下:

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

上一篇:ASP.NET中上传并读取Excel文件数据示例

栏    目:.NET代码

下一篇:一步步教你在Asp.net Mvc中使用UEditor编辑器

本文标题:使用Barrier来控制线程同步示例

本文地址:http://www.codeinn.net/misctech/191711.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有