使用AutoResetEvent同步两个线程 [英] Synchronizing two threads with AutoResetEvent

查看:111
本文介绍了使用AutoResetEvent同步两个线程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试实现AutoResetEvent.为此,我使用一个非常简单的类:

I'm trying to implement 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.

推荐答案

问题不是很清楚,但是我猜您希望它显示1,2,1,2 ...

The question is not very clear but I'm guessing you're expecting it to display 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();
    }
}

这篇关于使用AutoResetEvent同步两个线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆