import java.text.SimpleDateFormat;
import java.util.Date;
public class Test01 {
public static void main(String[] args) {
SimpleDateFormat sdf = new SimpleDateFormat("Y-M-d HH:mm:ss");
Thread t1 = new Thread() {
@Override
public void run() {
while (true) {
System.out.println(sdf.format(new Date()));
try {
Thread.sleep(1000 * 5);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
};
t1.start();
System.out.println(111);
}
}
不使用join时,会打印111,并且线程t1也会每隔5秒钟打印一次时间
加上t1.join()之后,不会再打印111,而是要等待线程t1执行完毕之后再打印111
import java.text.SimpleDateFormat;
import java.util.Date;
public class Test01 {
public static void main(String[] args) {
SimpleDateFormat sdf = new SimpleDateFormat("Y-M-d HH:mm:ss");
Thread t1 = new Thread() {
@Override
public void run() {
while (true) {
System.out.println(sdf.format(new Date()));
try {
Thread.sleep(1000 * 5);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
};
t1.start();
try {
t1.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(111);
}
}
可见join的作用就是将线程t1加入到主线程,且要等待t1线程执行完,主线程才会继续往下执行