线程之后台线程(一)

先看个例子:

using System;
using System.Threading;

namespace ThreadExample
{
	class c2
	{
		static void Main()
		{
			Thread t1 = new Thread( ThreadFun2 )
			{ Name = "Thread1", IsBackground = true };
			t1.Start();
			Console.WriteLine( "Main thread ending now." );
			Thread.Sleep( 6000 );
			Thread t2 = new Thread( ThreadFun2 )
			{ Name = "Thread2", IsBackground = true };
			t2.Start();
		}
		
		static void ThreadFun2()
		{
			Console.WriteLine( "Thread {0} started.", Thread.CurrentThread.Name );
			Thread.Sleep( 3000 );
			Console.WriteLine( "Thread {0} completed.", Thread.CurrentThread.Name );
		}
	}
}


运行结果:

Main thread ending now.
Thread Thread1 started.
Thread Thread1 completed.
Thread Thread2 started.

t1线程起来后,前台线程还没结束,所以t1的信息都打了出来,t2起来后,前台线程刚好结束,t2也被强行中止,所以t2只输出了一行信息。

去掉下面这行代码再试试:

			Thread.Sleep( 6000 );

运行了3次的结果:

D:\>ThExa2.exe
Main thread ending now.
Thread Thread1 started.

D:\>ThExa2.exe
Main thread ending now.
Thread Thread1 started.
Thread Thread2 started.

D:\>ThExa2.exe
Main thread ending now.
Thread Thread1 started.
Thread Thread2 started.

第一次运行,前台线程结束时,t1只输出一行信息,t2还没输出信息就被结束。

后2次运行,t2只输出一行信息,在sleep期间,刚好前台线程结束,2个后台线程被迫结束,再无信息输出。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值