Montior实现加锁

public class MonitorThreadTest
{
    static int count =0 ;
    public static void Run(){
        Stopwatch stopwatch = Stopwatch.StartNew();
        Thread thread1 = new Thread(new ThreadStart(AddCount));
        Thread thread2 = new Thread(new ThreadStart(AddCount));
        thread1.Start();
        thread2.Start();
        thread1.Join();
        thread2.Join();
        stopwatch.Stop();
        System.Console.WriteLine($"总数:{count},时间:{stopwatch.Elapsed}毫秒");
    }
    private static Object lockObj = new object();
    public static void AddCount(){
        Monitor.Enter(lockObj);
        for(int i=0; i<1000000; i++){
            count++;
        }
        Monitor.Exit(lockObj);
    }
}

 

posted @ 2023-11-28 07:44  vba是最好的语言  阅读(18)  评论(0编辑  收藏  举报