2013-01-23 41 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(); 
    } 
}