2013-01-23 39 views
8

我正在嘗試執行AutoResetEvent。爲了這個目的,我使用了一個非常簡單的類:使用AutoResetEvent同步兩個線程

public class MyThreadTest 
{ 
    static readonly AutoResetEvent thread1Step = new AutoResetEvent(false); 
    static readonly AutoResetEvent thread2Step = new AutoResetEvent(false); 

    void DisplayThread1() 
    { 
     while (true) 
     { 
      Console.WriteLine("Display Thread 1"); 

      Thread.Sleep(1000); 
      thread1Step.Set(); 
      thread2Step.WaitOne(); 
     } 
    } 

    void DisplayThread2() 
    { 
     while (true) 
     { 
      Console.WriteLine("Display Thread 2"); 
      Thread.Sleep(1000); 
      thread2Step.Set(); 
      thread1Step.WaitOne(); 
     } 
    } 

    void CreateThreads() 
    { 
     // construct two threads for our demonstration; 
     Thread thread1 = new Thread(new ThreadStart(DisplayThread1)); 
     Thread thread2 = new Thread(new ThreadStart(DisplayThread2)); 

     // start them 
     thread1.Start(); 
     thread2.Start(); 
    } 

    public static void Main() 
    { 
     MyThreadTest StartMultiThreads = new MyThreadTest(); 
     StartMultiThreads.CreateThreads(); 
    } 
} 

但是這不起作用。這個用法看起來非常直截了當,如果有人能夠告訴我什麼是錯誤的,那麼我在這裏實現的邏輯問題在哪裏,我將不勝感激。

+0

它是如何不加工?怎麼了? – SLaks

+0

那麼你給的代碼甚至不會編譯 - 你從來沒有聲明'_stopThreads' ... –

+0

@ Jon Skeet我只是改變代碼來隔離問題,現在它已經修復了。 – Leron

回答

19

的問題不是很清楚,但我猜你期待它來顯示1,2,1,2 ......

那就試試這個:

public class MyThreadTest 
{ 
    static readonly AutoResetEvent thread1Step = new AutoResetEvent(false); 
    static readonly AutoResetEvent thread2Step = new AutoResetEvent(true); 

    void DisplayThread1() 
    { 
     while (true) 
     { 
      thread2Step.WaitOne(); 
      Console.WriteLine("Display Thread 1"); 
      Thread.Sleep(1000); 
      thread1Step.Set(); 
     } 
    } 

    void DisplayThread2() 
    { 
     while (true) 
     { 
      thread1Step.WaitOne(); 
      Console.WriteLine("Display Thread 2"); 
      Thread.Sleep(1000); 
      thread2Step.Set(); 
     } 
    } 

    void CreateThreads() 
    { 
     // construct two threads for our demonstration; 
     Thread thread1 = new Thread(new ThreadStart(DisplayThread1)); 
     Thread thread2 = new Thread(new ThreadStart(DisplayThread2)); 

     // start them 
     thread1.Start(); 
     thread2.Start(); 
    } 

    public static void Main() 
    { 
     MyThreadTest StartMultiThreads = new MyThreadTest(); 
     StartMultiThreads.CreateThreads(); 
    } 
}