线程安全小练习
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); } } }
相关推荐
Hy 2020-11-13
xrslt 2020-11-06
yutian0 2020-10-26
杨树 2020-09-21
zhuyonge 2020-08-01
zhuyonge 2020-07-26
xiaoemo0 2020-07-18
fraternityjava 2020-06-26
luohui 2020-06-26
dxyadc 2020-06-26
luohui 2020-06-21
三动 2020-06-21
fengyun 2020-06-14
fraternityjava 2020-06-14
waitui00 2020-06-14
fraternityjava 2020-06-10
shayuchaor 2020-06-07