java 等待线程/线程池执行完毕
2017-08-07 15:43
417 查看
1.单线程开始并执行完毕
当线程开始后,需要用到join的方法
不废话直接贴代码
运行结果:
现在我们来看一下join这个方法
2.等待线程池执行完毕
等待线程池执行完毕我们需要用到
CountDownLatch这个类
且看代码:
最后一定要记得线程池关闭, 要不会出大问题的
运行结果:
当线程开始后,需要用到join的方法
不废话直接贴代码
public static void main(String args[]) { long begin = System.currentTimeMillis(); System.out.println(begin); Thread thread = new Thread(new Runnable() { @Override public void run() { try { Thread.sleep(1000L); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("111"); } }); try { thread.start(); thread.join(); } catch (InterruptedException e) { e.printStackTrace(); } long end = System.currentTimeMillis(); System.out.println(end-begin); System.out.println("执行完毕"); }
运行结果:
1502091332017 111 1002 执行完毕
现在我们来看一下join这个方法
/** * Waits for this thread to die. * * <p> An invocation of this method behaves in exactly the same * way as the invocation * * <blockquote> * {@linkplain #join(long) join}{@code (0)} * </blockquote> * * @throws InterruptedException * if any thread has interrupted the current thread. The * <i>interrupted status</i> of the current thread is * cleared when this exception is thrown. */ public final void join() throws InterruptedException { join(0); } 翻译为中文大意就是,等待线程执行完毕!
2.等待线程池执行完毕
等待线程池执行完毕我们需要用到
CountDownLatch这个类
且看代码:
public static void main(String args[]) throws InterruptedException { final CountDownLatch count = new CountDownLatch(3); ExecutorService fixedThreadPool = Executors.newFixedThreadPool(3); try { long begin = System.currentTimeMillis(); System.out.println(begin); fixedThreadPool.execute(new Runnable() { @Override public void run() { try { Thread.sleep(1000L); count.countDown(); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("111"); } }); fixedThreadPool.execute(new Runnable() { @Override public void run() { try { Thread.sleep(2000L); count.countDown(); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("222"); } }); fixedThreadPool.execute(new Runnable() { @Override public void run() { try { Thread.sleep(3000L); count.countDown(); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("333"); } }); count.await(); long end = System.currentTimeMillis(); System.out.println(end-begin); System.out.println("执行完毕"); } finally { fixedThreadPool.shutdown(); } }
最后一定要记得线程池关闭, 要不会出大问题的
运行结果:
1502091739441 111 222 333 3002 执行完毕
相关文章推荐
- java多线程实现主线程等待所有子线程执行完毕
- java主线程等待所有子线程执行完毕在执行(常见面试题)
- java主线程等待所有子线程执行完毕在执行
- Java主线程等待所有子线程执行完毕再执行解决办法集
- 两个带有线程池的方法分别执行两组线程任务,第二个方法需要等待第一组任务执行完毕
- Java主线程等待所有子线程执行完毕再执行解决办法
- Java主线程等待所有子线程执行完毕再执行解决办法集
- Java多线程--让主线程等待所有子线程执行完毕
- Java主线程等待所有子线程执行完毕再执行解决办法集
- Java多线程--让主线程等待所有子线程执行完毕
- Java多线程、主线程等待所有子线程执行完毕、共享资源
- Java主线程等待所有子线程执行完毕再执行解决办法
- 线程池等待一定数目的线程执行完毕之后返回结果
- Java多线程--让主线程等待所有子线程执行完毕代码
- Java等待多个线程执行完毕
- Java多线程--主线程等待所有子线程执行完毕
- Java中等待提交线程池的所有线程执行完成
- java主线程等待所有子线程执行完毕在执行(常见面试题)
- java 等待所有线程执行完毕
- Java多线程--让主线程等待所有子线程执行完毕