主题:求助!編程題,不是求答案!
用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不可以這樣用嗎??
請解答,謝謝
以下是我的代碼:
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不可以這樣用嗎??
請解答,謝謝