Advertisement
sergAccount

Untitled

Jan 30th, 2021
605
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.55 KB | None | 0 0
  1. /*
  2.  * To change this license header, choose License Headers in Project Properties.
  3.  * To change this template file, choose Tools | Templates
  4.  * and open the template in the editor.
  5.  */
  6. package com.mycompany.app5;
  7.  
  8. import java.util.concurrent.ExecutionException;
  9. import java.util.concurrent.ExecutorService;
  10. import java.util.concurrent.Executors;
  11. import java.util.concurrent.Future;
  12. import java.util.concurrent.TimeUnit;
  13.  
  14. public class Main2 {    
  15.     public static void main(String[] args) {        
  16.         try {
  17.             // ExecutorService executor = Executors.newFixedThreadPool(5);
  18.             ExecutorService executor = Executors.newFixedThreadPool(5);
  19.             // 1) запуск задачи типа Runnable, используем лямбда выражение
  20.             Runnable r = () -> {System.out.println("do something...");};
  21.             executor.submit(r);
  22.             executor.submit(new MyTask1());
  23.             Future<String> result = executor.submit(new MyCallableTask());
  24.             // 1) Ожидаем выполнение задачи и полуаем результат после ее завершения - используем метод get()
  25. //            String res = result.get();
  26. //            System.out.println("res=" + res);
  27.             // 2) Проверяем статус выполнения задачи (используем метод isDone()) result и после ее выполения вызываем метод get()
  28.             while(!result.isDone()){
  29.                 System.out.println("MyCallableTask is running...");
  30.                 TimeUnit.SECONDS.sleep(1);
  31.             }
  32.             String res = result.get();
  33.             System.out.println("res=" + res);
  34.            
  35.            
  36.             // ожидаем некоторое время для выполнения задач
  37.             TimeUnit.SECONDS.sleep(2);
  38.             // прекраащем выполнение пула потоков
  39.             //executor.shutdownNow(); // shutdownNow - принудительное завершение
  40.             //executor.shutdown();  // shutdown-ожидаем завершения, новые задачи запустить уже нельзя
  41.              
  42.         } catch (InterruptedException ex) {
  43.             ex.printStackTrace();
  44.         } catch (Exception ex) {
  45.             ex.printStackTrace();
  46.         }        
  47.     }    
  48. }
  49. class MyTask1 implements Runnable{
  50.     @Override
  51.     public void run() {        
  52.         System.out.println("MyTask.run");
  53.     }                
  54. }
  55.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement