c#多线程数据共享解决办法之一:lock排它锁

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
namespace 多线程数据共享
{
    class Program
    {
        static bool lockOrNot;
        static int i=1;
        static readonly object locker = new object();

        static void Main(string[] args)
        {
            //多个线程执行了相同的方法
            Thread mythread = new Thread(new ThreadStart(go));
            mythread.Start();
            Thread mythread2 = new Thread(new ThreadStart(go));
            mythread2.Start();
            Thread mythread3 = new Thread(new ThreadStart(go));
            mythread3.Start();
            Thread mythread4 = new Thread(new ThreadStart(go));
            mythread4.Start();
            Thread mythread5 = new Thread(new ThreadStart(go));
            mythread5.Start();

            Console.ReadKey();
        }
        static void go()
        {
            lock (locker)
            {
                i++;
                Thread.Sleep(50);
                Console.WriteLine("i={0},我是线程{1}", i,
                    Thread.CurrentThread.ManagedThreadId);
            }

            //i++;
            //Thread.Sleep(50);
            //Console.WriteLine("i={0},我是线程{1}", i, 
            //    Thread.CurrentThread.ManagedThreadId);
        }
    }
}

 

你可能感兴趣的:(C#)