[关闭]
@946898963 2022-05-25T20:55:31.000000Z 字数 1568 阅读 422

java并发之awaitTermination的使用

Java


  1. public static ExecutorService executorService = Executors.newFixedThreadPool(10);
  2. public static void main(String[] args) throws InterruptedException {
  3. executorService.submit(() -> System.out.println(Thread.currentThread().getName()));
  4. long curTime = System.currentTimeMillis();
  5. boolean b = executorService.awaitTermination(3, TimeUnit.SECONDS);
  6. long lastTime = System.currentTimeMillis();
  7. System.out.println("duration:" + (lastTime - curTime) + " result:" + b);
  8. }
  1. pool-1-thread-1
  2. duration:3004 result:false
  1. public static ExecutorService executorService = Executors.newFixedThreadPool(10);
  2. public static void main(String[] args) throws InterruptedException {
  3. executorService.submit(() -> System.out.println(Thread.currentThread().getName()));
  4. executorService.shutdown();
  5. long curTime = System.currentTimeMillis();
  6. boolean b = executorService.awaitTermination(3, TimeUnit.SECONDS);
  7. long lastTime = System.currentTimeMillis();
  8. System.out.println("duration:" + (lastTime - curTime) + " result:" + b);
  9. }
  1. pool-1-thread-1
  2. duration:0 result:true
  1. public static ExecutorService executorService = Executors.newFixedThreadPool(10);
  2. public static void main(String[] args) throws InterruptedException {
  3. executorService.submit(() -> System.out.println(Thread.currentThread().getName()));
  4. new Thread(() -> {
  5. try {
  6. Thread.sleep(1000);
  7. } catch (InterruptedException e) {
  8. e.printStackTrace();
  9. }
  10. executorService.shutdown();
  11. }).start();
  12. long curTime = System.currentTimeMillis();
  13. boolean b = executorService.awaitTermination(3, TimeUnit.SECONDS);
  14. long lastTime = System.currentTimeMillis();
  15. System.out.println("duration:" + (lastTime - curTime) + " result:" + b);
  16. }
  1. pool-1-thread-1
  2. duration:1004 result:true
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注