简体   繁体   English

使用AutoResetEvent同步两个线程

[英]Synchronizing two threads with AutoResetEvent

I'm trying to implement AutoResetEvent . 我正在尝试实现AutoResetEvent For the purpose I use a very simple class : 出于这个目的,我使用一个非常简单的类:

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();
    }
}

But this is not working. 但这不起作用。 Th usage seem very straight-forward so I would appreciate if someone is able to show me what's wrong and where is the problem with the logic which i implement here. 用法看起来非常简单,所以如果有人能够告诉我什么是错的,我会很感激,我在这里实现的逻辑问题在哪里。

The question is not very clear but I'm guessing you're expecting it to display 1,2,1,2... 问题不是很明确,但我猜你期待它显示1,2,1,2 ......

Then try this: 然后尝试这个:

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();
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM