- Join 方法
该方法可以让并发行处理变成串行化,具体看下面代码。
static void Main(string[] args)
{
Thread thread = new Thread(new ThreadStart(Run));
thread.Start();
thread.Join();
// 该死的t.Join(),害的我主线程必须在你执行完后才能执行。
Console.WriteLine("我是主线程:" + Thread.CurrentThread.GetHashCode());
Console.ReadLine();
}
public static void Run()
{
//Thread.
Thread.Sleep(1000);
Console.WriteLine("我是子线程线程:" + Thread.CurrentThread.GetHashCode());
}
运行结果:
结论:
MainThread 在 NewThread.Join() 被调用后被阻塞,直到 NewThread 执行完毕才继续执行。
应用场景:
该join方法主要应用场景是多个方法的执行具有先后顺序。其实就是将线程进行并行化处理或者可以说成阻塞调用线程,直到某个线程终止时为止。
2. Interrupt和Abort
这两个关键字都是用来强制终止线程,Interrupt主要是中止处于 Wait或者Sleep或者Join 线程状态的线程;Abort则表示直接终止线程运行
如果一个线程处于了阻塞状态(如线程调用了thread.sleep、thread.join、thread.wait、1.5中的condition.await、以及可中断的通道上的 I/O 操作方法后可进入阻塞状态),则在线程在检查中断标示时如果发现中断标示为true,则会在这些阻塞方法(sleep、join、wait、1.5中的condition.await及可中断的通道上的 I/O 操作方法)调用处抛出InterruptedException异常,并且在抛出异常后立即将线程的中断标示位清除,即重新设置为false。抛出异常是为了线程从阻塞状态醒过来,并在结束线程前让程序员有足够的时间来处理中断请求。
Interrupt代码:
static void Run()
{
for (int i = 1; i <= 3; i++)
{
Stopwatch watch = new Stopwatch();
try
{
watch.Start();
Thread.Sleep(2);
watch.Stop();
Console.WriteLine("第{0}延迟执行:{1}ms", i, watch.ElapsedMilliseconds);
}
catch (ThreadInterruptedException e)
{
Console.WriteLine("第{0}延迟执行:{1}ms,不过抛出异常", i, watch.ElapsedMilliseconds);
}
catch (ThreadAbortException e)
{
Console.WriteLine("abort异常");
}
}
}
static void Main(string[] args)
{
Thread t = new Thread(new ThreadStart(Run));
t.Start();
//阻止动作
t.Abort();
Console.Read();
}
Abort代码:
static void Run()
{
for (int i = 1; i <= 3; i++)
{
Stopwatch watch = new Stopwatch();
try
{
watch.Start();
Thread.Sleep(2);
watch.Stop();
Console.WriteLine("第{0}延迟执行:{1}ms", i, watch.ElapsedMilliseconds);
}
catch (ThreadInterruptedException e)
{
Console.WriteLine("第{0}延迟执行:{1}ms,不过抛出异常", i, watch.ElapsedMilliseconds);
}
catch (ThreadAbortException e)
{
Console.WriteLine("abort异常");
}
}
}
static void Main(string[] args)
{
Thread t = new Thread(new ThreadStart(Run));
t.Start();
//阻止动作
t.Interrupt();
Console.Read();
}