博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
主线程结束之后,所有的子线程都结束
阅读量:4356 次
发布时间:2019-06-07

本文共 1192 字,大约阅读时间需要 3 分钟。

using System;

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

namespace ConPra

{
    class Program
    {
        //主线程结束之后,所有的子线程都结束
        public static void Main(string[] Args)
        {
            Thread t1;
            Thread t2;
            t1 = new Thread(new ThreadStart(PrintfAllDatasThread1));
            t2 = new Thread(new ThreadStart(PrintfAllDatasThread2));
            t1.IsBackground = true;
            t2.IsBackground = true;
            t1.Start();

            //与下面的代码一样的功能

            //while (t1.ThreadState!=ThreadState.Stopped)
            //{
            //    Thread.Sleep(20);
            //}

            //while (t1.IsAlive)

            //{
            //    Thread.Sleep(20);               
            //}
            t1.Join();//表示当t1线程运行结束之后,主线程才能执行
            Console.WriteLine(t1.ThreadState.ToString() + " " + t1.IsAlive);
            t2.Start();

            while (t2.ThreadState != ThreadState.Stopped)

            {

            }

        }

 

        public static void PrintfAllDatasThread1()
        {
            for (int i = 0; i < 10; i++)
            {

                System.Threading.Thread.Sleep(200);

                Console.Write("当前线程ID=" + Thread.CurrentThread.ManagedThreadId + "  " + i);
            }

        }

        public static void PrintfAllDatasThread2()

        {
            for (int i = 0; i < 100; i++)
            {
                System.Threading.Thread.Sleep(200);
                Console.Write("当前线程ID=" + Thread.CurrentThread.ManagedThreadId + "  " + i);
            }
        }
    }
}

转载于:https://www.cnblogs.com/ganquanfu2008/archive/2013/04/25/3043484.html

你可能感兴趣的文章
解析xlsx与xls--使用2012poi.jar
查看>>
java5,java6新特性
查看>>
【LOJ】#2290. 「THUWC 2017」随机二分图
查看>>
SSL-ZYC 活动安排
查看>>
Git clone 报错 128
查看>>
在Python中执行普通除法
查看>>
编译原理(第三版) 语法分析器
查看>>
c# 动态绘制直线和曲线
查看>>
Spring理解?
查看>>
删除无限循环的文件夹-删除递归文件夹
查看>>
Test
查看>>
C# 整理
查看>>
AngularJS中使用$resource
查看>>
[poj3261]Milk Patterns(后缀数组)
查看>>
[luogu3369]普通平衡树(fhq-treap模板)
查看>>
题解 P2799 【国王的魔镜】
查看>>
写写代码,注意注意细节
查看>>
css Backgroud-clip (文字颜色渐变)
查看>>
安装 OpenSSL 工具
查看>>
用长微博工具发布长微博
查看>>