zoukankan      html  css  js  c++  java
  • 线程同步信号量的使用

         //******本期测试内容:在线程同步中使用信号量********
            //声明 自动信号传达对象 AutoResetEvent 只能处理单个使用autoReset进行线程阻塞的线程
            AutoResetEvent autoReset = new AutoResetEvent(false);
            //声明 手动信号传达对象 ManualResetEvent 可以处理所有使用manualRest进行线程阻塞的线程
            ManualResetEvent manualRest = new ManualResetEvent(false);
            public ThreadTest()
            {
                InitializeComponent();
            }
    
            private void button1_Click(object sender, EventArgs e)
            {
                test1();
                test2();
            }
            private void test1()
            {
                Thread t = new Thread(() =>
                {
                    MessageBox.Show("开始同步线程等待,等待信号传入");
                    bool re = autoReset.WaitOne(10000);
                    if (re)
                    {
                        MessageBox.Show("收到激活线程命令");
                    }
                    else
                    {
                        MessageBox.Show("未收到激活线程命令");
                    }
                });
                t.Start();
            }
            private void test2()
            {
                Thread t = new Thread(() =>
                {
                    MessageBox.Show("开始同步线程等待,等待信号传入1");
                    bool re = autoReset.WaitOne(10000);
                    if (re)
                    {
                        MessageBox.Show("收到激活线程命令1");
                    }
                    else
                    {
                        MessageBox.Show("未收到激活线程命令1");
                    }
                });
                t.Start();
            }
    
            private void button2_Click(object sender, EventArgs e)
            {
                //传递 激活线程信号,立马激活线程 跳出等待
                autoReset.Set();
            }

     AutoResetEvent 在发送完信号之后 自动将自己设置为false状态,所以  第二个线程 接收不到信号。

  • 相关阅读:
    Oracle、Db2、SqlServer、MySQL 数据库插入当前系统时间
    Mybatis---在控制台打印sql语句
    多线程实现的四种方法
    Restful架构
    maven中的pom配置文件一——spring,mybatis,oracle,jstl,json,文件上传
    spring mvc配置
    spring的事务
    cglib动态代理
    jdk动态代理
    spring总结————AOP面向切面总结
  • 原文地址:https://www.cnblogs.com/scyr/p/7338081.html
Copyright © 2011-2022 走看看