我想對隊列進行一些測試,並使用Queue.Synchronized查看當兩個線程將東西放入隊列中時它是如何工作的,以及第三個線程是將它讀出來的。這看起來很簡單,但它不能正常工作,我不知道爲什麼。可能是我的一個愚蠢的錯誤。儘管如此,還有一點。我的隊列行事有趣,任何想法爲什麼?
class Program
{
public int this1 = 0;
static void Main(string[] args)
{
Tester test1 = new Tester();
Queue myQ = new Queue();
Tester.myQ = Queue.Synchronized(myQ);
Thread test1_thread = new Thread(new ThreadStart(test1.test1));
Thread test1_thread2 = new Thread(new ThreadStart(test1.test1));
test1_thread.Start();
test1_thread2.Start();
int i = 0;
while (i <= 10)
{
i++;
go_back_here:
try
{
Tester.myQ.Enqueue(40);
Console.WriteLine("did it");
int holding = Convert.ToInt32(Tester.myQ.Dequeue());
Console.WriteLine("reading out {0}: {1}", i);
}
catch
{
//Console.Write("e");
//goto go_back_here;
}
}
Console.ReadLine();
}
}
class Tester
{
public static Queue myQ;
public void test1()
{
int this1 = 0;
while (this1 <= 10)
{
Console.WriteLine("Doing something {0}", this1);
myQ.Enqueue(this1);
Console.WriteLine("(peek) {0}", myQ.Dequeue());
this1++;
}
}
}
通過我自己的測試,我發現兩個測試器線程正在將東西加載到隊列中。當我的主循環嘗試將它出隊時,我會收到一個錯誤,說隊列是空的。我把Peeks和Dequeues放在測試線程中,他們能夠在線程中顯示這些東西。因此我添加了「Tester.myQ.Enqueue(40);」,因此我想知道如果我是從主循環訪問錯誤的隊列(OOP不是我的專長,仍在學習它),所以我添加了「Tester.myQ.Enqueue(40);」看看我是否可以在其中插入一些東西。我的peeks/Dequeues沒有顯示它,但是,當我添加「完成」寫入行時,它顯示出來了。我已經運行了這個程序了很多次,並且主循環中的40只出現在測試線程打印出來的Dequeue中,當「did it」在那裏。從來沒有當我評論它。
有人對這個問題有更多的瞭解可以瞭解發生了什麼嗎? (是的,我知道我使用goto是一件可怕的事情,我讓它滑動,因爲這應該是一個簡單的測試)
呃哦,你用了'goto',你是否檢查['rapters?](http://xkcd.com/292):) – 2010-10-17 04:45:26