C#多线程---Mutex类实现线程同步

一、例子

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5 using System.Threading;
 6 using System.Threading.Tasks;
 7 
 8 namespace ThreadMutex
 9 {
10     class Program
11     {
12         private static Mutex mutex = new Mutex();
13         private static int sum = 0;
14         static void Main(string[] args)
15         {
16             Task<int> task = new Task<int>(ThreadFunction);
17             task.Start();
18             Console.WriteLine($"{DateTime.Now} task started!");
19             Thread.Sleep(2000);
20             mutex.WaitOne();
21             Console.WriteLine($"{DateTime.Now} Get siginal in main!");
22             Console.WriteLine($"{DateTime.Now} Result is {task.Result}");
23         }
24         private static int ThreadFunction()
25         {
26             mutex.WaitOne();
27             for (int i = 0; i < 10; i++)
28             {
29                 sum  += i;
30                 Thread.Sleep(1000);
31             }
32             Console.WriteLine($"{DateTime.Now} Release mutex in ThreadFunction!");
33             mutex.ReleaseMutex();
34         
35             return sum;
36         }
37     }
38 }
View Code

运行结果如下:

 

转载于:https://www.cnblogs.com/3xiaolonglong/p/9651010.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值