欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

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

程序员文章站 2023-12-18 21:03:10
可能的输出:复制代码 代码如下:working on thread aworking on thread bthread b will sleep for 10 secon...

可能的输出:

复制代码 代码如下:

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

上一篇:

下一篇: