C#多线程---Mutex类实现线程同步
2021-06-27 20:05
标签:private static size display view start rgs img res 一、例子 运行结果如下: C#多线程---Mutex类实现线程同步 标签:private static size display view start rgs img res 原文地址:https://www.cnblogs.com/3xiaolonglong/p/9651010.html 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 Taskint> task = new Taskint>(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 }