问题描述:当需要需要多个子线程执行完之后,主线程再执行之后代码(顺序执行),举例如下
Threadthread1 = new Thread();
Threadthread2 = new Thread();
Threadthread3 = new Thread();
thread1.start();
thread2.start();
thread3.start();
System.out.println("mainthread run"); //在thread1,2,3,跑完之后再执行。
方法如下:
一、采用join()方法
thread1.start();
thread2.start();
thread3.start();
thread1.join();
thread2.join();
thread3.join();
System.out.println("mainthread run");
二、使用CountDownLatch类(固定长度)
CountDownLatch cl = new CountDownLatch(3);
public void run() {
//TODO Auto-generated method stub
System.out.println(currentThread().getName()+"run");
cl.countDown();//注意在末尾,建议放在 finally里执行
}
thread1.start();
thread2.start();
thread3.start();
cl.await();
三、使用Runtime.getRuntime().addShutdownHook(Thread)
Runtime.getRuntime().addShutdownHook(newThread(){
@Override
publicvoid run() {
//TODO Auto-generated method stub
//最后执行代码
}
});
addShutdownHook添加的关闭挂钩,是在java虚拟机关闭前执行,但是,有些时候,子线程运行完毕后,并不期望程序退出,可能还有其它的任务,甚至有可能程序是一个长时间运行的服务器,那就更不可能随便停止了。这种情况下,关闭挂钩就无能为力了,而CountDownLatch则没有这种限制,较之灵活性更强。
四、使用CyclicBarrier(周期屏蔽)
CyclicBarriercb = new CyclicBarrier(3, new Runnable() {
@Override
publicvoid run() {
//TODO Auto-generated method stub
//后面执行代码
}
});
publicvoid run() {
System.out.println("before");
cb.await();所有线程在此处等待,直到最后一个线程完成之前作业,才往后执行。
System.out.println("after");
}
五、使用ThreadGroup、ReadWriteLock等,欢迎补充!