如果没有经过特殊处理,线程和线程之间是并行运行的,如何让它们串行执行呢?
(1)一种是使用无参的join(),等到另一个线程执行完毕再继续运行;
(2)一种是使用带参的join(long millis) ,等待一定的时间后,无论另一个线程是否执行完毕,都继续执行。
public class Thread1 extends Thread {
@Override
public void run() {
System.out.println("线程Thread1开始执行");
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("线程Thread1执行完毕");
}
}
public class Thread2 extends Thread {
private Thread1 thread1;
public Thread2(Thread1 thread1) {
this.thread1 = thread1;
}
@Override
public void run() {
try {
// 时间超过了1000ms,则放弃等待,继续执行
thread1.join(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("线程Thread2开始执行");
System.out.println("线程Thread2执行完毕");
}
public static void main(String[] args) {
Thread1 t1 = new Thread1();
Thread2 t2 = new Thread2(t1);
t1.start();
t2.start();
}
}
原文地址:http://blog.51cto.com/13855604/2171806