C#中lock,Monitor和Mutex的测试代码
2015-07-06 11:20
525 查看
关于lock,Monitor和Mutex他们同一线程不互斥的测试代码如下:
lock
Mutex
Monitor
lock
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; namespace TestThread { class Program { static void Main(string[] args) { Thread t1 = new Thread(ThreadFunc1); Thread t2 = new Thread(ThreadFunc2); t1.Start(); t2.Start(); } private static object obj = new object(); private static Mutex m = new Mutex(); static void ThreadFunc1() { lock (obj) { for (int i = 0; i < 10; i++) { lock (obj) { Func("ThreadFunc1"); } } } } static void ThreadFunc2() { lock (obj) { for (int i = 0; i < 10; i++) { lock (obj) { Func("ThreadFunc2"); } } } } static void Func(string str) { Console.WriteLine("{0} {1}", str, System.DateTime.Now.Millisecond.ToString()); Thread.Sleep(500); } } }
Mutex
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; namespace TestThread { class Program { static void Main(string[] args) { Thread t1 = new Thread(ThreadFunc1); Thread t2 = new Thread(ThreadFunc2); t1.Start(); t2.Start(); } private static object obj = new object(); private static Mutex m = new Mutex(); static void ThreadFunc1() { m.WaitOne(); for (int i = 0; i < 10; i++) { m.WaitOne(); Func("ThreadFunc1"); m.ReleaseMutex(); } m.ReleaseMutex(); } static void ThreadFunc2() { m.WaitOne(); for (int i = 0; i < 10; i++) { m.WaitOne(); Func("ThreadFunc2"); m.ReleaseMutex(); } m.ReleaseMutex(); } static void Func(string str) { Console.WriteLine("{0} {1}", str, System.DateTime.Now.Millisecond.ToString()); Thread.Sleep(500); } } }
Monitor
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; namespace TestThread { class Program { static void Main(string[] args) { Thread t1 = new Thread(ThreadFunc1); Thread t2 = new Thread(ThreadFunc2); t1.Start(); t2.Start(); } private static object obj = new object(); private static Mutex m = new Mutex(); static void ThreadFunc1() { Monitor.Enter(obj); for (int i = 0; i < 10; i++) { Monitor.Enter(obj); Func("ThreadFunc1"); Monitor.Exit(obj); } Monitor.Exit(obj); } static void ThreadFunc2() { Monitor.Enter(obj); for (int i = 0; i < 10; i++) { Monitor.Enter(obj); Func("ThreadFunc2"); Monitor.Exit(obj); } Monitor.Exit(obj); } static void Func(string str) { Console.WriteLine("{0} {1}", str, System.DateTime.Now.Millisecond.ToString()); Thread.Sleep(500); } } }
相关文章推荐
- [C#] 如何获取项目的根目录
- C# 获取电脑硬盘剩余空间
- C#画图消除锯齿
- C#多线程系列
- C#线程等待句柄
- [转载]C#特性详解
- C#正则表达式匹配双引号
- 验证(C#和正则表达式)
- C#注册表操作汇总
- C#编写简单的聊天程序
- C#编写简单的聊天程序
- C#设计模式(4)——抽象工厂模式(Abstract Factory)
- C#设计模式——工厂方法模式(Factory Method)
- C#设计模式——单例模式(Singleton)
- C#注释及说明
- C# webbroswer屏蔽脚本错误
- 多线程端口扫描源码(C#)
- C# 课堂总结3-语句
- C# Kinect 2.0 SDK 学习笔记(0)——基本情况介绍
- c#作业第5期