开启多个线程,每个线程中多次操作公共变量
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个线程 Animal a = new Animal();
for (int i = ; i < ; i++)
{
Thread t = new Thread(a.Add1); //10 个线程同时执行方法 Add1 threads[i] = t;
}
for (int i = ; i < ; i++)
{
threads[i].Start(); //启动线程
} Console.ReadLine();
} } public class Animal
{
int balance = ;
private object obj = new object();
public void Add1()
{
for (int i = ; i < ; i++) //每个线程执行1000次Withdraw1方法
{
Withdraw1(new Random().Next(, ));
}
}
public void Withdraw1(int a)
{
if (balance < )
{ throw new Exception("为负了"); } //不加锁,就会抛出该异常,加锁后不会抛出
//lock (obj)
//{
if (balance >= a)
{
Console.WriteLine("before"+balance);
Console.WriteLine("减去"+a);
balance = balance - a; //多线程情况下,此处balance 会被其他线程修改,造成负值
Console.WriteLine("剩余" + balance);
}
//} } } }