Thread.join方法
join方法只有在线程结束时才继续执行下面的语句(会依次执行)。可以对每一个线程调用它的join方法,但要注意,这个调用要在另一个线程里,而不要在主线程,否则程序会被阻塞的。在调用join前先要Start开启线程
看一个阻塞主线程的方法
static void Main(string[] args)
{
int ms = 1000;
Thread thread1 = new Thread(Mymethod);
thread1.Name = "thread1";
Thread thread2 = new Thread(Mymethod);
thread2.Name = "thread2";
Thread thread3 = new Thread(Mymethod);
thread3.Name = "thread3";
for (int i = 0; i < 10; i++)
{
Console.WriteLine("主线程工作了 " + i.ToString() + " 次.");
if (i == 5)
{
Thread[] tr = new Thread[] { thread1, thread2, thread3 };
foreach (Thread t in tr)
{
t.Start(ms);
t.Join();
}
}
}
Console.ReadKey();
}
private static void Mymethod(object obj)
{
Thread.Sleep(Int32.Parse(obj.ToString()));
Console.WriteLine(Thread.CurrentThread.Name.ToString() + "结束任务用时:" + obj);
}
执行效果如图
把Join不放在主线程中执行
class Program
{
static void Main(string[] args)
{
int ms = 1000;
Thread thread1 = new Thread(Mymethod);
thread1.Name = "thread1";
Thread thread2 = new Thread(Mymethod);
thread2.Name = "thread2";
Thread thread3 = new Thread(Mymethod);
thread3.Name = "thread3";
thread1.Start(100);
thread2.Start(2000);
thread3.Start(3000);
for (int i = 0; i < 10; i++)
{
Console.WriteLine("主线程工作了 " + i.ToString() + " 次.");
Thread.Sleep(1000);
}
Thread joinThread = new Thread(JoinAllThread);
joinThread.Start(new Thread[] { thread1, thread2, thread3 });
Console.ReadKey();
}
private static void JoinAllThread(object obj)
{
Thread[] threads = obj as Thread[];
foreach (Thread t in threads)
{
t.Join();
}
}
private static void Mymethod(object obj)
{
Thread.Sleep(Int32.Parse(obj.ToString()));
Console.WriteLine(Thread.CurrentThread.Name.ToString() + "结束任务用时:" + obj);
}
}
执行效果如图
定义一个线程类
我们可以将Thread类封装在一个MyThread类中,以使任何从MyThread继承的类都具有多线程能力。MyThread类的代码如下
class Program : MyThread
{
static void Main(string[] args)
{
Program nt = new Program();
nt.start();
Console.ReadKey();
}
override public void run()
{
Console.WriteLine("使用MyThread建立并运行线程");
}
}
abstract class MyThread
{
Thread thread = null;
abstract public void run();
public void start()
{
if (thread == null)
thread = new Thread(run);
thread.Start();
}
}