C# AutoResetEvent

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;

namespace ConsoleApplication6
{
    class CountTest
    {
        private int count = 0;
        public int Count
        {
            get { return count; }
            set { count = value; }
        }

        public void Increment()
        {
            count++;
        }

        public void Decrement()
        {
            count--;
        }
    }


    class Program
    {
        private static AutoResetEvent Event_1 = new AutoResetEvent(true);       

        static void TestCounter(CountTest c)
        {
            Console.WriteLine("{0} 请求互斥锁", Thread.CurrentThread.Name);
            Event_1.WaitOne();
            Console.WriteLine("\n{0} 已获得互斥锁", Thread.CurrentThread.Name);
            for (int i = 0; i < 1000000; i++)
            {
                c.Increment();
                c.Decrement();
            }
            Event_1.Set();
            Console.WriteLine("{0} 已获释放斥锁", Thread.CurrentThread.Name);
            Thread.Sleep(500);
        }

        static void Main(string[] args)
        {

            var tc = new CountTest();
            for (int i = 1; i <= 4; i++)
            {
                Thread MyThread = new Thread(() => TestCounter(tc));
                MyThread.Name = string.Format("Thread_{0}",i);
                MyThread.Start();
                MyThread.Join();
            }                     

            Console.WriteLine("\n计算结果为:{0} ", tc.Count);
            Console.Read();

        }
    }
}

 

相关文章:

  • 2022-02-15
  • 2021-07-18
  • 2021-09-05
  • 2022-02-25
  • 2021-07-01
猜你喜欢
  • 2021-08-15
  • 2022-02-15
  • 2022-12-23
  • 2022-12-23
  • 2022-03-10
相关资源
相似解决方案