rss· 投稿· 设为首页· 加入收藏· 繁體版
当前位置: 火魔网 » 程序开发 » C#

[MK Code]线程计数器(C# Sample)

/*
* Created by SharpDevelop.
* User: MK
* Date: 2009-3-24
* 线程计数器
*/
using System;
using System.Threading;
namespace ThreadTest
{
    public abstract class MyThread
    {
        Thread _thread;
        public MyThread()
        {
            if (_thread == null)
                _thread = new Thread(run);
            _thread.IsBackground = false;
        }
        abstract protected void run();
        public bool isBackground
        {
            set
            {
                _thread.IsBackground = value;
            }
        }
        public void Start()
        {
            _thread.Start();
        }
    }
    class ThreadCounter : MyThread
    {
        private static int count = 0;
        private int ms;
        private static void increment()
        {
            lock (typeof(ThreadCounter))  // 必须同步计数器
            {
                count++;
            }
        }
        private static void decrease()
        {
            lock (typeof(ThreadCounter))
            {
                count--;
            }
        }
        private static int getCount()
        {
            lock (typeof(ThreadCounter))
            {
                return count;
            }
        }
        public ThreadCounter(int ms)
        {
            this.ms = ms;
            increment();
        }
        override protected void run()
        {
            Thread.Sleep(ms);
            Console.WriteLine(ms.ToString() + "毫秒任务结束");
            decrease();
            if (getCount() == 0)
                Console.WriteLine("所有任务结束");
        }
    }
    class Program
    {
        static void Main()
        {
            ThreadCounter t1 = new ThreadCounter(5000);
            ThreadCounter t2 = new ThreadCounter(3000);
            ThreadCounter t3 = new ThreadCounter(4000);
            t1.Start();
            t2.Start();
            t3.Start();
            Console.ReadKey();
        }
    }
}
顶一下
(0)
踩一下
(0)