package java_learning;
//using join() to wait thread to finish
class NewThread implements Runnable{
String m_name;
Thread m_t;
NewThread(String threadname){
m_name = threadname;
m_t = new Thread(this, m_name);
System.out.println("New thread:"+m_name);
m_t.start(); // Start the thread
}
@Override
public void run() {
// TODO 自动生成的方法存根
try {
for(int i = 5; i > 0; i--) {
System.out.println(m_name + ": " + i);
Thread.sleep(1000);//让其他线程有时间运行
}
} catch (InterruptedException e) {
System.out.println(m_name + " interrupted.");
}
System.out.println(m_name + " exiting.");
}
}
public class DemoJoin{
public static void main(String[]args){
NewThread ob1 = new NewThread("thread1");
NewThread ob2 = new NewThread("thread2");
NewThread ob3 = new NewThread("thread3");
System.out.println("Thread1 is alive:"+ob1.m_t.isAlive());
System.out.println("thread1 is alive:"+ob2.m_t.isAlive());
System.out.println("thread1 is alive:"+ob3.m_t.isAlive());
// wait for threads to finish,希望主线程最后结束
//join()方法等待所调用线程结束。该名字来自于要求线程等待直到指定线程参与的概念。
//join()的附加形式允许给等待指定线程结束定义一个最大时间。
//运用join()以确保主线程最后结束。
try {
System.out.println("Waiting for threads to finish.");
ob1.m_t.join();//等待ob1线程结束
ob2.m_t.join();//等待ob2线程结束
ob3.m_t.join();//等待ob3线程结束
} catch (InterruptedException e) {
System.out.println("Main thread Interrupted");
}
System.out.println("Thread One is alive: "+ ob1.m_t.isAlive());
System.out.println("Thread Two is alive: "+ ob2.m_t.isAlive());
System.out.println("Thread Three is alive: "+ ob3.m_t.isAlive());
System.out.println("Main thread exiting.");
}
}
运行结果:
New thread:thread1
New thread:thread2
thread1: 5
New thread:thread3
thread2: 5
Thread1 is alive:true
thread1 is alive:true
thread1 is alive:true
Waiting for threads to finish.
thread3: 5
thread1: 4
thread3: 4
thread2: 4
thread1: 3
thread3: 3
thread2: 3
thread1: 2
thread3: 2
thread2: 2
thread1: 1
thread3: 1
thread2: 1
thread1 exiting.
thread3 exiting.
thread2 exiting.
Thread One is alive: false
Thread Two is alive: false
Thread Three is alive: false
Main thread exiting.