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状态,所以  第二个线程 接收不到信号。

  • 相关阅读:
    AVL Trees & Huffman Tree
    线索二叉树
    w10 端口转发
    springboot 注解属性配置
    java 性能分析工具
    JAVA
    ffmpeg ffplay播放延时大问题:播放延时参数设置
    springboot jodconverter openoffice 实现 office 文件 在线预览
    oracle 字符串 正则表达式 拆分,排序,合并
    润乾填报-(自定义)自动计算
  • 原文地址:https://www.cnblogs.com/scyr/p/7338081.html
Copyright © 2011-2022 走看看