• 线程安全小练习


     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 }
  • 相关阅读:
    css中的属性
    css初识和css选择器
    前端html的简单认识
    数据库进阶了解
    数据库索引
    pymysql模块
    数据库的多表查询
    数据库中的行操作
    数据库和表操作以及完整性约束
    数据库概述
  • 原文地址:https://www.cnblogs.com/anyihen/p/12828172.html
Copyright © 2020-2023  润新知