我的这段代码中,Thread.Sleep(500);即设为绿色背景的那句代码,为什么会影响counter打印出来的数量?,我这个打印出来counter的值只有 0 1 2,有哪位大神能够指导下
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
namespace DestoryThread
{
class Program
{
static void Main(string[] args)
{
ThreadStart childref = new ThreadStart(CallToChildThread);
Console.WriteLine("In Main : Creating The Child Thread");
Thread childThread = new Thread(childref);
childThread.Start();
//停止主线程一段时间
Thread.Sleep(2000);
//终止子线程
Console.WriteLine("In Main : Aborting The Child Thread");
childThread.Abort();
Console.ReadKey();
}
public static void CallToChildThread()
{
try
{
Console.WriteLine("Child Thread Starts");
for (int counter = 0; counter <= 10; counter++)
{
Thread.Sleep(500);
Console.WriteLine(counter);
}
Console.WriteLine("Child Thread Completed");
}
catch (ThreadAbortException e)
{
Console.WriteLine("Thread Abort Exception");
}
finally
{
Console.WriteLine("Couldn't Catch the Thread Exception");
}
}
}
}
childThread.Abort();
这个干嘛?好好活着不行么?你改成childThread.Join()不就完了?
恩恩!谢谢啦,我懂啦
线程调用线程会出现线程之间的冲突,在本例中,主线程先调用了CallToChildThread线程,但是主线程还是在进行。主线程的等待时间是2s ,而CallToChildThread中counter打印等待的时间是0.5s,当CallToChildThread中执行到2的时候,主线程已经调用了Abort()方法,所以整个线程结束,counter也只能打印到2