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

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

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用法的全部内容,更多相关多线程内容请搜索靠谱客的其他文章。

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

评论列表共有 0 条评论

立即
投稿
返回
顶部