亲宝软件园·资讯

展开

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

人气:0
想了解使用Barrier来控制线程同步示例的相关内容吗,在本文为您仔细讲解Barrier线程同步的相关知识和一些Code实例,欢迎阅读和指正,我们先划重点: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; }
    }
}

加载全部内容

相关教程
猜你喜欢
用户评论