开启多个线程,每个线程中多次操作公共变量
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); } //} } } }