fengyun 2020-05-04
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using System.Threading; namespace WindowsFormsApplication3 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } //lock只能锁定一个引用类型变量 private static object _lock = new object(); private void button1_Click(object sender, EventArgs e) { //new Thread(Done).Start(); //new Thread(Done).Start(); //new Thread(Done).Start(); //new Thread(Done).Start(); new Thread(Done1).Start(); new Thread(Done1).Start(); new Thread(Done1).Start(); new Thread(Done1).Start(); } void Done() { //lock只能锁定一个引用类型变量 lock (_lock) { tasktest(); } } void Done1() { Monitor.Enter(_lock); { tasktest(); } Monitor.Exit(_lock); } private void tasktest() { for (int i = 0; i < 5; i++) { Thread.Sleep(1000); } Console.WriteLine("test" + Thread.CurrentThread.ManagedThreadId); } } }