using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;
//using System.Diagnostics;namespace 多线程
{#region 我的程序class ResultCount{public static int PassNumber { get; set; }public static int FailNumber { get; set; }}class Program{private static object _lock = new object();static void Main(string[] args){Thread[] threadArray = new Thread[10];for (int i = 0; i < 10; i++){threadArray[i] = new Thread(new ThreadStart(PassCountAdd));}foreach (var item in threadArray){item.Start();}foreach (var item in threadArray){//Join: 一个同步方法,该方法阻止调用线程 (即,调用方法的线程) ,直到 Join 调用方法的线程完成。//使用此方法可以确保线程已终止。 如果线程未终止,调用方将无限期阻止。 在下面的示例中,//Thread1 线程调用的 Join() 方法 Thread2 ,这会导致 Thread1 一直阻止到 Thread2 完成为止。item.Join();}Console.WriteLine(ResultCount.PassNumber);Console.WriteLine(ResultCount.FailNumber);}static void PassCountAdd(){for (int i = 0; i < 100000; i++){lock (_lock){ResultCount.PassNumber++;ResultCount.FailNumber++;}}}}#endregion#region Microsoft官网例程//public class Example//{//    static Thread thread1, thread2;//    public static void Main()//    {//        thread1 = new Thread(new ThreadStart(ThreadProc));//        thread1.Name = "Thread1";//        thread1.Start();//        thread2 = new Thread(new ThreadStart(ThreadProc));//        thread2.Name = "Thread2";//        thread2.Start();//    }//    private static void ThreadProc()//    {//        Console.WriteLine("\nCurrent thread: {0}", Thread.CurrentThread.Name);//        if (Thread.CurrentThread.Name == "Thread1"//            && (thread2.ThreadState != ThreadState.Unstarted))//        {//            //Join: 一个同步方法,该方法阻止调用线程 (即,调用方法的线程) ,直到 Join 调用方法的线程完成。//            //使用此方法可以确保线程已终止。 如果线程未终止,调用方将无限期阻止。 在下面的示例中,//            //Thread1 线程调用的 Join() 方法 Thread2 ,这会导致 Thread1 一直阻止到 Thread2 完成为止。//            thread2.Join();//        }//        Thread.Sleep(4000);//        Console.WriteLine("\nCurrent thread: {0}", Thread.CurrentThread.Name);//        Console.WriteLine("Thread1: {0}", thread1.ThreadState);//        Console.WriteLine("Thread2: {0}", thread2.ThreadState);//    }//}#endregion
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;namespace ConsoleApplication1
{public static class MyLock  //使用同一把锁对同一资源进行互斥访问保护{public static object _lock = new object();}class Program{static void Main(string[] args){Student stu1 = new Student(1, "Tom", ConsoleColor.Green);Student stu2 = new Student(2, "Jerry", ConsoleColor.Yellow);Student stu3 = new Student(3, "Jason", ConsoleColor.Red);#region 使用Action委托//Action action1 = new Action(stu1.DoHomeWork);//Action action2 = new Action(stu2.DoHomeWork);//Action action3 = new Action(stu3.DoHomeWork);//action1.BeginInvoke(null, null);//action2.BeginInvoke(null, null);//action3.BeginInvoke(null, null);#endregion#region Thread多线程//Thread thread1 = new Thread(new ThreadStart(stu1.DoHomeWork));//Thread thread2 = new Thread(new ThreadStart(stu2.DoHomeWork));//Thread thread3 = new Thread(new ThreadStart(stu3.DoHomeWork));//thread1.Start();//thread2.Start();//thread3.Start();#endregion#region Task多线程Task task1 = new Task(new Action(stu1.DoHomeWork));Task task2 = new Task(new Action(stu2.DoHomeWork));Task task3 = new Task(new Action(stu3.DoHomeWork));task1.Start();task2.Start();task3.Start();#endregionfor (int i = 0; i < 10; i++){lock(MyLock._lock){Console.ForegroundColor = ConsoleColor.White;Console.WriteLine("Main thread{0}!", i + 1);}Thread.Sleep(100);}}}class Student{public int Id { get; set; }public string Name { get; set; }public ConsoleColor Color { get; set; }public Student(int id, string name, ConsoleColor color){Id = id;Name = name;Color = color;}public void DoHomeWork(){for (int i = 0; i < 5; i++){lock(MyLock._lock){Console.ForegroundColor = Color;Console.WriteLine("Id:{0},Name:{1},Color:{2}, doing homework {3}hours.",Id, Name, Console.ForegroundColor, i + 1);}Thread.Sleep(100);}}}
}

C#多线程时对同一资源加锁实现互斥访问相关推荐

  1. 如何避免操作系统中多线程资源竞争的互斥与同步?

    作者 | 小林coding 来源 | 小林coding(ID:CodingLin) 前言 先来看看虚构的小故事 已经晚上 11 点了,程序员小明的双手还在键盘上飞舞着,眼神依然注视着的电脑屏幕. 没办 ...

  2. 架构设计 | 高并发流量削峰,共享资源加锁机制

    本文源码:GitHub·点这里 || GitEE·点这里 一.高并发简介 在互联网的业务架构中,高并发是最难处理的业务之一,常见的使用场景:秒杀,抢购,订票系统:高并发的流程中需要处理的复杂问题非常多 ...

  3. 线程基础知识_线程生命周期_从JVM内存结构看多线程下的共享资源

    线程生命周期 线程状态 New: 线程创建(new Thread()) Runnable: 线程可运行(thread.start()), 注: 调用start并不一定是运行状态, 可能在等待CPU调度 ...

  4. 多线程时,出现段错误

    问题: 1. 单线程运行没有任何问题, 多线程时,有时会莫名出现段错误,但程序的结果是完全正确的. 过段时间后,段错误又会自动修复. 2. 多线程速度反而慢.

  5. excel 2010创建透视表时提示内存资源不足

    excel 2010创建透视表时提示内存资源不足 我的系统是win7 32位 4G内存 求解!网上也搜了好多试过 也不行............................ 本文转自xinrenb ...

  6. 并发编程系列之五多线程synchronized是可重复加锁,重入锁

    并发编程系列之五多线程synchronized是可重复加锁,重入锁.对于重入锁的概念就是可以重复的加锁.. 示例1,在同一个类里面进行加锁,不同的方法调用,都一层一层的嵌套进行加锁,示例1演示重入锁的 ...

  7. [饥荒联机版模组]修改制作栏中的合成物品时的需要资源和其它相关技巧

    此文章只是记录编写联机版mod时做的记录,不是一篇很正式的文档 想要入门饥荒mod制作,可以看同站的夏湾作者文章,很详细~ 直接给代码和结论,目前在饥荒是可用的 修改制作栏中的合成物品时的需要资源 - ...

  8. Visual Studio C# 项目生成时复制项目资源目录到生成目录

    关键词:C#, C#项目, csproj, Visual Studio, VS, MSBuild, output, debug, 项目生成, 复制 关联搜索标题: C# Visual Studio 项 ...

  9. 秒杀多线程第七篇 经典线程同步 互斥量Mutex

    阅读本篇之前推荐阅读以下姊妹篇: <秒杀多线程第四篇一个经典的多线程同步问题> <秒杀多线程第五篇经典线程同步关键段CS> <秒杀多线程第六篇经典线程同步事件Event& ...

最新文章

  1. 18岁双料竞赛金牌得主邓明扬:我只是数学初学者,求在MIT“活”下去
  2. 【数据】短视频识别,都有那些行业标准?
  3. Boost:双图bimap与散列索引的测试程序
  4. Adroid真机调试
  5. 300plc与组态王mpi通讯_S7-300与S7-200之间的MPI通信
  6. 中科罗伯特机器人吧_延庆旧县南站附近继续教育
  7. 开源软件没你想象中那么安全,Java 开发者尤其要警惕
  8. 区块链开发人员短缺?各大公司献上连环招
  9. Cisco交换机密码忘记重置
  10. pytorch 测试每一类_2D UNet++ VGGBlock脑胶质瘤分割BraTs + Pytorch实现
  11. .NET伪静态使用以及和纯静态的区别
  12. php阴影效果,css阴影效果:css边框阴影如何设置?
  13. erase函数的用法
  14. mysql提权(mof udf 反弹端口)
  15. 惠普HP LaserJet Pro P1106 打印机驱动
  16. word关闭时卡死_如何修复卡死的Mac
  17. Datakit.CrossManager.2023(2D/3D数据格式转换器)
  18. 某招聘网站“数据分析”相关岗位招聘信息爬取并分析
  19. cufflinks之cuffmerge,cuffdiff
  20. SSM框架介绍与搭建

热门文章

  1. SharedPreferences保存对象以及集合,腾讯MMKV使用,保存搜索历史
  2. highcharts x轴 按照时间 datetime排序
  3. vscode设置折行字数
  4. centos 生产 ssh-key
  5. 学校计算机二级模拟上机能看分数吗,全国计算机二级考试机试考完怎么储存的...
  6. JDK8后的日期时间API
  7. java 字符过滤器_Java Web---登录验证和字符编码过滤器
  8. 计算机键盘标注,你所不知道的 Windows 10 小诀窍:万能计算器、虚拟键盘、屏幕截图标注...
  9. HDU 1176 免费馅饼 (动态规划、另类数塔)
  10. [Alg] 二叉树的非递归遍历