我是靠谱客的博主 含糊冷风,这篇文章主要介绍多线程的并发问题,lock用法,现在分享给大家,希望可以做个参考。

开启多个线程,每个线程中多次操作公共变量

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Threading; namespace TestLock { class Program { static void Main(string[] args) { Test1(); } public static void Test1() { Thread[] threads = new Thread[10]; //开启10个线程 Animal a = new Animal(); for (int i = 0; i < 10; i++) { Thread t = new Thread(a.Add1); //10 个线程同时执行方法 Add1 threads[i] = t; } for (int i = 0; i < 10; i++) { threads[i].Start(); //启动线程 } Console.ReadLine(); } } public class Animal { int balance = 1000; private object obj = new object(); public void Add1() { for (int i = 0; i < 1000; i++) //每个线程执行1000次Withdraw1方法 { Withdraw1(new Random().Next(1, 100)); } } public void Withdraw1(int a) { if (balance < 0) { throw new Exception("为负了"); } //不加锁,就会抛出该异常,加锁后不会抛出 //lock (obj) //{ if (balance >= a) { Console.WriteLine("before"+balance); Console.WriteLine("减去"+a); balance = balance - a; //多线程情况下,此处balance 会被其他线程修改,造成负值 Console.WriteLine("剩余" + balance); } //} } } }

 

最后

以上就是含糊冷风最近收集整理的关于多线程的并发问题,lock用法的全部内容,更多相关多线程内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(86)

评论列表共有 0 条评论

立即
投稿
返回
顶部