• 线程安全小练习


     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 }
  • 相关阅读:
    Linux软件安装中RPM与YUM 区别和联系(转载)
    linux文件系统
    (转载) linux基础知识
    linux学习:硬盘挂载
    IDEA版github教程(转载)
    idea配置gitee(转载)
    事与人的关系
    maven打包失败与问题反思
    计算机开机
    maven到底干了啥
  • 原文地址:https://www.cnblogs.com/anyihen/p/12828172.html
Copyright © 2020-2023  润新知