[color=red] [b] 在线程操作中,可以使用Thread类的join()或join(long millis)方法让一个线程强制执行,线程强制执行期间,其他线程无法运行,必须等待此线程完成之后才可以继续运行。[/b][/color]
运行结果:
public class MyThread implements Runnable{
@Override
public void run() {
for(int i=0;i<5;i++){
System.out.println(Thread.currentThread().getName()+"运行-->"+i);
}
}
}
public class ThreadJoinDemo {
public static void main(String[] args){
MyThread myThread=new MyThread();
Thread t=new Thread(myThread,"线程");
t.start();
for(int i=0;i<5;i++){
if(i>2){
try {
t.join();
} catch (InterruptedException ex) {
Logger.getLogger(ThreadJoinDemo.class.getName()).log(Level.SEVERE, null, ex);
}
}
System.out.println("Main 线程运行-->"+i);
}
}
}
运行结果:
Main 线程运行-->0
Main 线程运行-->1
Main 线程运行-->2
线程运行-->0
线程运行-->1
线程运行-->2
线程运行-->3
线程运行-->4
Main 线程运行-->3
Main 线程运行-->4