public class ab implements Runnable{
public void run(){
for(int i = 0 ; i < 4000 ; i++)
System.out.println(i);
}
public static void main(String[] args){
Thread thread = new Thread(new ab());
thread.start();
System.out.println("Started");
try {
thread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Complete");
}
}
Join()方法使得某个线程加入到正在执行的线程中,本题是main线程,执行完该线程才继续执行main线程.本程序中第5行由main线程执行,6行因为下达了join(),所以mian的执行将被暂停,等t做完run()方法的全部工作之后,才论到main继续执行未完成的工作!
我们可以将join方法去掉就可以看到串"Compele"和"Started"串一下就就打印出来,而不会等待线程的执行完,再打印出"Complete",也就是两个线程各做各的,谁也不等谁。