通過線程計數器和Thread.Join方法得到線程已完成狀態

方法一:線程計數器


    class Program
    {
        static void Main(string[] args)
        {
            Thread[] ths = new Thread[3];

            ThreadCounter counter1 = new ThreadCounter(1000);
            ThreadCounter counter2 = new ThreadCounter(3000);
            ThreadCounter counter3 = new ThreadCounter(7000);

            Thread countera = new Thread(new ThreadStart(counter1.run));
            Thread counterb = new Thread(new ThreadStart(counter2.run));
            Thread counterc = new Thread(new ThreadStart(counter3.run));

            countera.Start();
            counterb.Start();
            counterc.Start();

            Console.ReadKey();
        }
    }

    class ThreadCounter
    {
        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)
        {
            Increment();
            this.ms = ms;
        }

        public void run()
        {
            Thread.Sleep(ms);
            Console.WriteLine(ms.ToString() + "毫秒任務結束");
            Decrease();
            if (getCount() == 0)
            {
                Console.WriteLine("-------所有任務結束-------");
            }
        }
    }

方法二:Thread.Join方法

    class Program
    {
        static void Main(string[] args)
        {
            ThreadJoin join1 = new ThreadJoin(1000);
            ThreadJoin join2 = new ThreadJoin(3000);
            ThreadJoin join3 = new ThreadJoin(7000);
            Thread th1 = new Thread(new ThreadStart(join1.run));
            Thread th2 = new Thread(new ThreadStart(join2.run));
            Thread th3 = new Thread(new ThreadStart(join3.run));

            ThreadJoin join = new ThreadJoin();
            join.Join(new Thread[] { th1, th2, th3 });

            Console.ReadKey();
        }
    }

    class ThreadJoin
    {
        private int ms;
        public ThreadJoin()
        {

        }

        public ThreadJoin(int ms)
        {
            this.ms = ms;
        }

        public void run()
        {
            Thread.Sleep(ms);
            Console.WriteLine(ms + "毫秒任務結束");
        }

        public void Join(object[] obj)
        {
            Thread[] ths = obj as Thread[];
            foreach (Thread th in ths)
            {
                th.Start();
                th.Join();
            }
            Console.WriteLine("所有線程結束");
        }
    }

轉載自:http://developer.51cto.com/art/200908/147794.htm 自己做了修改

推薦:http://www.laikanxia.com

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章