Advertisement
sergAccount

Untitled

Jan 30th, 2021
594
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.84 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.             // 3) Ожидаем выполнение задачи определенное время - используем метод get() с параметром
  35.              String res = result.get(10, TimeUnit.SECONDS);
  36.              System.out.println("res=" + res);
  37.            
  38.            
  39.             // ожидаем некоторое время для выполнения задач
  40.             TimeUnit.SECONDS.sleep(2);
  41.             // прекраащем выполнение пула потоков
  42.             //executor.shutdownNow(); // shutdownNow - принудительное завершение
  43.             //executor.shutdown();  // shutdown-ожидаем завершения, новые задачи запустить уже нельзя
  44.              
  45.         } catch (InterruptedException ex) {
  46.             ex.printStackTrace();
  47.         } catch (Exception ex) {
  48.             ex.printStackTrace();
  49.         }        
  50.     }    
  51. }
  52. class MyTask1 implements Runnable{
  53.     @Override
  54.     public void run() {        
  55.         System.out.println("MyTask.run");
  56.     }                
  57. }
  58.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement