zoukankan      html  css  js  c++  java
  • 线程安全小练习

     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 删除多余IP地址
    linux 变更网卡后无法联网
    eureka 参数
    C# 一般处理程序使用session注意事项
    asp.net web 简单使用cookie
    asp.net ajax post 请求
    Ajax 的基本使用以及get请求
    asp.net 错误页
    C# winfrom 跨线程访问文本框
    C# winfrom 打印到Excel中
  • 原文地址:https://www.cnblogs.com/anyihen/p/12828172.html
Copyright © 2011-2022 走看看