join();等待线程运行结束
public class Test02 {
static int r = 0;
public static void main(String[] args) throws InterruptedException {
test();
}
private static void test() throws InterruptedException {
System.out.println(Thread.currentThread().getName()+"开始");
Thread t1 = new Thread(new Runnable() {
@Override
public void run() {
System.out.println(Thread.currentThread().getName()+"开始");
r = 10;
System.out.println(Thread.currentThread().getName()+"结束");
}
},"t1");
t1.start();
System.out.println(Thread.currentThread().getName()+"结果" + r);
}
}
主线程直接执行,输出r;
public class Test02 {
static int r = 0;
public static void main(String[] args) throws InterruptedException {
test();
}
private static void test() throws InterruptedException {
System.out.println(Thread.currentThread().getName()+"开始");
Thread t1 = new Thread(new Runnable() {
@Override
public void run() {
System.out.println(Thread.currentThread().getName()+"开始");
r = 10;
System.out.println(Thread.currentThread().getName()+"结束");
}
},"t1");
t1.start();
//主线程等待t1线程运行结束
t1.join();
System.out.println(Thread.currentThread().getName()+"结果" + r);
}
}
主线程等待t1线程执行结束