关于Thread实例的join代表的含义,先直接看代码和运行结果
public class Main {
public static void main(String[] args) {
DemoRunnable demo1 = new DemoRunnable(null);
Thread t1 = new Thread(demo1,"thread-demo-1");
DemoRunnable demo2 = new DemoRunnable(t1);
Thread t2 = new Thread(demo2,"thread-demo-2");
Thread t3 = new Thread(demo2,"thread-demo-3");
t1.start();
t2.start();
t3.start();
}
static class DemoRunnable implements Runnable{
private Thread t;
public DemoRunnable(Thread t){
this.t= t;
}
@Override
public void run() {
if(t != null){
try {
t.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
for(int i=0; i<10; i++){
System.out.println(Thread.currentThread().getName()+" "+i);
}
}
}
}
运行结果:
thread-demo-1 0
thread-demo-1 1
thread-demo-1 2
thread-demo-1 3
thread-demo-1 4
thread-demo-1 5
thread-demo-1 6
thread-demo-1 7
thread-demo-1 8
thread-demo-1 9
thread-demo-3 0
thread-demo-2 0
thread-demo-2 1
thread-demo-3 1
thread-demo-3 2
thread-demo-2 2
thread-demo-3 3
thread-demo-2 3
thread-demo-3 4
thread-demo-2 4
thread-demo-3 5
thread-demo-2 5
thread-demo-3 6
thread-demo-2 6
thread-demo-3 7
thread-demo-2 7
thread-demo-3 8
thread-demo-2 8
thread-demo-3 9
thread-demo-2 9
由此可以分析知:join的意思是,告诉其他的线程,我正在执行,执行完毕后你在执行.join()方法提高了当前线程的优先级,一直抢占着CpU