join and sleep
- 调用join()方法,就可以等待另一个线程结束。
- 调用join(参数) ,可以设置一个超时,用毫秒或者TimeSpan. 此时有返回值 在超时时间内,如果线程执行结束了返回true 否false
- Thread.Sleep(参数)方法。 线程阻塞,到设定时间后继续执行。
注意:
Thread.Sleep(0) 这样调用会导致线程会立即放弃本身当前时间片,自动将CPU移交给其他线程。和Thread.YieId()做同样事。 但是YIEID只会把执行交给同一处理器的其他线程。
for text One
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
namespace ConsolePlan
{
class Program
{
static void Main(string[] args)
{
Thread.CurrentThread.Name = "Main Thread ConsolePlan...";
Thread threadText = new Thread(PrintChar);
threadText.IsBackground = true;
threadText.Name = "SubThread Name...";
threadText.Start();
//等待子线程执行完毕在执行主线程
threadText.Join();
Console.WriteLine(Thread.CurrentThread.Name);
for (int i = 0; i < 1000; i++)
{
Console.Write('X');
}
Console.ReadKey(true);
}
static void PrintChar()
{
Console.WriteLine(Thread.CurrentThread.ThreadState);
Console.WriteLine(Thread.CurrentThread.Name);
for (int i = 0; i < 1000; i++)
{
Console.Write('Y');
}
}
}
}
for text Two
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
namespace ConsolePlan
{
class Program
{
private static Thread SubThreadOne, SubThreadTwo;
private readonly static string SubThrOneName = "Thread1";
private const string SubThrTwoName = "Thread2";
static void Main(string[] args)
{
SubThreadOne = new Thread(Go);
SubThreadOne.Name = SubThrOneName;
SubThreadOne.Start();
SubThreadTwo = new Thread(Go);
SubThreadTwo.Name = SubThrTwoName;
SubThreadTwo.Start();
Console.ReadKey(true);
}
static void Go()
{
string curName = Thread.CurrentThread.Name;
Console.WriteLine("\nThread Name {0} Thread ID {1}", curName, Thread.CurrentThread.ManagedThreadId);
if (curName == SubThrOneName && SubThreadTwo.ThreadState != ThreadState.Unstarted)
{
SubThreadTwo.Join();
}
Thread.Sleep(4000);
Console.WriteLine("\n Current Thread Name {0}",curName);
Console.WriteLine(SubThreadOne.ThreadState);
Console.WriteLine(SubThreadTwo.ThreadState);
}
}
}
当前执行结果:
for Text Three
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
namespace ConsolePlan
{
class Program
{
private static TimeSpan SleepTime = new TimeSpan(0, 0, 1);
static void Main(string[] args)
{
Thread thread = new Thread(Text);
thread.Name = "SubThread";
thread.Start();
if (thread.Join(SleepTime))
{
Console.WriteLine("thread run end...");
}
else
{
Console.WriteLine("{0} Join Timed out..",thread.Name);
Console.WriteLine("ThreadState: {0} ThreadIsalive: {1}",thread.ThreadState,thread.IsAlive);
}
Console.ReadKey(true);
}
static void Text()
{
Thread.Sleep(SleepTime);
}
}
}