C#多线程---Mutex类实现线程同步
2024-08-31 22:30:36
一、例子
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 }
运行结果如下:
最新文章
- Ubuntu Desktop开发生产环境搭建
- code vs 1026 逃跑的拉尔夫
- linux连接12tp vpn
- 远程出发jenkins jobs
- ECMAScript6-下一代Javascript标准
- Java中正则Matcher类的matches()、lookAt()和find()的区别<;转>;
- 学习总结 html一般标签的使用
- Git教程之标签管理
- Android分类前言
- bootstrap初探
- python re(正则模块)
- Japanese Learning - Words and Sentences 1
- ABP 教程文档 1-1 手把手引进门之 AngularJs, ASP.NET MVC, Web API 和 EntityFramework(官方教程翻译版 版本3.2.5)含学习资料
- 原来你是这样的Websocket--抓包分析
- 通过一个tomcat端口访问多个tomcat项目 tomcat转发
- Java高并发 -- 线程池
- KMP algorithm challenge string.Contains
- netty源码解解析(4.0)-6 线程模型-IO线程EventLoopGroup和NIO实现(一)
- JAVA代码设置selector不同状态下的背景
- struts2实现jQuery的异步交互
热门文章
- C语言:char总结
- bs4爬取笔趣阁小说
- post传参params与body的区别(@RequestParam和@RequestBody的区别)
- 【LeetCode】841. 钥匙和房间
- Tr0ll靶机
- [ZJOI2010]基站选址,线段树优化DP
- JSP的执行原理、JSP的内置对象、四大作用域解析、MVC模式理解>;从零开始学JAVA系列
- NOIP&;CSP PJ 难度刷题记录
- Python 统计列表中重复元素的个数并返回其索引值
- flight.Archives001 / CSS Selectors选择器