前一篇(对比):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();
}
}
}
}
运行结果