c#-线程实验-用状态+非循环控制线程

前一篇(对比):c#-线程实验-用状态+循环控制线程

说明

// 这里暂停。那么什么时候回继续执行呢?
 myThread.Suspend();
            //Thread.Sleep(1000 * 3 * 10);
            /*
            while (true) {
                if (fun1_end && fun2_end) {
                    break;
                }
            }
            */
            //Thread.CurrentThread.Resume();
            Console.WriteLine(num);

// 这里发现两个线程都已经计算完了,那么主线程继续执行
if (fun1_end && fun2_end)
            {
                myThread.Resume();
            }

代码 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;

namespace ConsoleApp4
{
    class Program
    {
        static int num=0;
        static bool fun1_end = false;
        static bool fun2_end = false;
        static Thread myThread;
        static void Main(string[] args)
        {
            myThread = Thread.CurrentThread;
            Console.WriteLine(Thread.CurrentThread.ManagedThreadId);
            Console.WriteLine("hello word\n");
            var thread1 = new Thread(fun1);
            var thread2 = new Thread(fun2);
            thread1.Start();
            thread2.Start();
            Thread.CurrentThread.Suspend();                      
            //Thread.Sleep(1000 * 3 * 10);
            /*
            while (true) {
                if (fun1_end && fun2_end) {
                    break;
                }
            }
            */
            Console.WriteLine(num);
            Console.ReadKey();
        }
        static void fun1() {
            Console.WriteLine(Thread.CurrentThread.ManagedThreadId);
            Console.WriteLine(Thread.CurrentContext.ToString());
            for (int i=0;i<10;i++) {
                Thread.Sleep(1000);
                num++;
            }
            fun1_end = true;
            if(fun1_end && fun2_end)
            {
                myThread.Resume();
            }
        }
        static void fun2()
        {
            Console.WriteLine(Thread.CurrentThread.ManagedThreadId);
            Console.WriteLine(Thread.CurrentContext.ToString());
            for (int i = 0; i < 10; i++){
                Thread.Sleep(1000);
                num++;
            }
            fun2_end = true;
            if (fun1_end && fun2_end)
            {
                myThread.Resume();
            }
        }
    }
}

运行结果 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值