回 帖 发 新 帖 刷新版面

主题:求助!編程題,不是求答案!

用Stack類儲存1-10的數值,創建2個獨立線程,設定名字,輪流取出Stack對象中數值,輸出控制臺,同時顯示線程名字.
以下是我的代碼:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
using System.Threading;

namespace ConsoleApplication1
{
    class P
    {
        Thread t1;
        Thread t2;
        public Stack<int> s = new Stack<int>();
        public P()
        {
            for (int i = 1; i < 11; i++)
            {
                s.Push(i);
            }
        }

        static void Main(string[] args)
        {
            P p = new P();
            p.ST();
        }

        void ST() 
        {
            Thread t1 = new Thread(new ThreadStart(Pop1));
            Thread t2 = new Thread(new ThreadStart(Pop2));
            t1.Name = "111";
            t2.Name = "222";
            t2.Start();
            t1.Start();
        }

        void Pop1() 
        {
            while (s.Count > 0)
            {
                Console.WriteLine
                    ("Thread {0}:{1}", Thread.CurrentThread.Name, s.Pop());
                t2.Join();
            }
        }

        void Pop2()
        {
            while (s.Count > 0)
            {
                Console.WriteLine
                    ("Thread {0}:{1}", Thread.CurrentThread.Name, s.Pop());
                t1.Join();
            }
        }
    }
}

雖然用Monitor也可以實現題目,但我想用Join.
運行時候出錯,是Join不可以這樣用嗎??
請解答,謝謝

回复列表 (共1个回复)

沙发

首先,按照你的思路
那两行应该这样吧
t1 = new Thread(new ThreadStart(Pop1));
t2 = new Thread(new ThreadStart(Pop2));

其次,这种方法会导致两线程只有一个运行然后另一个再运行或者全部死锁

我想你应该是要实现两个进程相互争抢输出的程序吧

我来回复

您尚未登录,请登录后再回复。点此登录或注册