某些时候,我们需要强制优先运行某线程,可以使用join()方法、join(long millis)、join(long millis,int nanos),后两个带参数中的方法的作用是,指定合并时间,前者精确到毫秒,后者精确到纳秒,意思是两个线程合并指定的时间后,又开始分离,回到合并千的状态。
public class ThreadJoin {
public static void main(String[] args){
ThreadTest t = new ThreadTest();
Thread pp = new Thread(t);
pp.start();
int i=0;
for(int x=0;x<10;x++){
if(x==4){
try{
pp.join(1000);//强制运行完一线程后,再运行后面的线程
}catch(Exception e){
System.out.println(e.getMessage());
}
}
System.out.println("main Thread"+i++);
}
}
}
public class ThreadTest implements Runnable{
public void run(){
int i=0;
for(int x=0;x<10;x++)
{
System.out.println(Thread.currentThread().getName()+"------>"+i++);
}
}
}