join()方法是指让主线程等待子线程结束后,才继续运行,并且同sleep()方法一样不会释放锁。
一.没有join()方法
public class MyThread1 implements Runnable {
private static int a = 0;
public static void main(String[] args) {
// TODO Auto-generated method stub
MyThread1 R = new MyThread1();
Thread t1 = new Thread(R);
t1.start();
System.out.println(Thread.currentThread().getName()+", main线程中: a = "+a);
}
@Override
public void run() {
// TODO Auto-generated method stub
print();
}
private void print() {
// TODO Auto-generated method stub
for(int i=0;i<5;i++){
a=a+1;
//System.out.println(Thread.currentThread().getName()+" i = "+i);
}
System.out.println(Thread.currentThread().getName()+", 线程t1中: a = "+a);
}
}
main线程中输出的结果是随机的:
情况一:
main, main线程中: a = 0
Thread-0, 线程t1中: a = 5
情况二:
main, main线程中: a = 5
Thread-0, 线程t1中: a = 5
二。如果想让main线程中输出的结果也是5,加入t1.join();方法
public class MyThread1 implements Runnable {
private static int a = 0;
public static void main(String[] args) {
// TODO Auto-generated method stub
MyThread1 R = new MyThread1();
Thread t1 = new Thread(R);
t1.start();
try {
t1.join();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+", main线程中: a = "+a);
}
@Override
public void run() {
// TODO Auto-generated method stub
print();
}
private void print() {
// TODO Auto-generated method stub
for(int i=0;i<5;i++){
a=a+1;
//System.out.println(Thread.currentThread().getName()+" i = "+i);
}
System.out.println(Thread.currentThread().getName()+", 线程t1中: a = "+a);
}
}
打出的log一定是下面的:
Thread-0, 线程t1中: a = 5
main, main线程中: a = 5
t1.join();这行代码在这里的作用,如果子线程t1没有执行完,是不会执行main线程的打印那行代码。
主线程和线程t1的运行状态如下图所示: