1 using System;
2 using System.Collections.Generic;
3 using System.ComponentModel;
4 using System.Data;
5 using System.Drawing;
6 using System.Linq;
7 using System.Text;
8 using System.Windows.Forms;
9 using System.Threading;
10
11 namespace WindowsFormsApplication3
12 {
13 public partial class Form1 : Form
14 {
15 public Form1()
16 {
17 InitializeComponent();
18 }
19
20 //lock只能锁定一个引用类型变量
21 private static object _lock = new object();
22 private void button1_Click(object sender, EventArgs e)
23 {
24 //new Thread(Done).Start();
25 //new Thread(Done).Start();
26 //new Thread(Done).Start();
27 //new Thread(Done).Start();
28
29
30 new Thread(Done1).Start();
31 new Thread(Done1).Start();
32 new Thread(Done1).Start();
33 new Thread(Done1).Start();
34
35 }
36 void Done()
37 {
38 //lock只能锁定一个引用类型变量
39 lock (_lock)
40 {
41 tasktest();
42 }
43 }
44 void Done1()
45 {
46 Monitor.Enter(_lock);
47 {
48 tasktest();
49 }
50 Monitor.Exit(_lock);
51 }
52
53
54
55 private void tasktest()
56 {
57 for (int i = 0; i < 5; i++)
58 {
59 Thread.Sleep(1000);
60 }
61
62 Console.WriteLine("test" + Thread.CurrentThread.ManagedThreadId);
63 }
64
65
66 }
67 }