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