用join()就行了吧
我直接写了3个线程试了下:
Thread t1 = new Thread(new Runnable() {
@Override
public void run() {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("t1...");
}
});
Thread t2 = new Thread(new Runnable() {
@Override
public void run() {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("t2...");
}
});
Thread t3 = new Thread(new Runnable() {
@Override
public void run() {
System.out.println("t3...");
}
});
t1.start();
t1.join();
t2.start();
t2.join();
t3.start();
我直接写了3个线程试了下:
Thread t1 = new Thread(new Runnable() {
@Override
public void run() {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("t1...");
}
});
Thread t2 = new Thread(new Runnable() {
@Override
public void run() {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("t2...");
}
});
Thread t3 = new Thread(new Runnable() {
@Override
public void run() {
System.out.println("t3...");
}
});
t1.start();
t1.join();
t2.start();
t2.join();
t3.start();
如果下一个的执行严格依赖之前的, 那就不要把任务往线程池里放了, 声明三个对象直接运行他们的run()方法是不是就哦了.
再就是有线程池, 就不能单独跑线程了? 不往里放也ok的呀~
// 等待子线程结束,再继续执行下面的代码
pool.awaitTermination(Long.MAX_VALUE, TimeUnit.DAYS);
pool.execute(new MyThread());
pool.awaitTermination(Long.MAX_VALUE, TimeUnit.DAYS);
pool.execute(new After());
pool.awaitTermination(Long.MAX_VALUE, TimeUnit.DAYS);