Advertisement
sergAccount

Untitled

Jan 30th, 2021
713
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.58 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.ExecutorService;
  9. import java.util.concurrent.Executors;
  10. import java.util.concurrent.TimeUnit;
  11.  
  12. public class Main2 {
  13.    
  14.     public static void main(String[] args) {        
  15.         try {
  16.             // ExecutorService executor = Executors.newFixedThreadPool(5);
  17.             ExecutorService executor = Executors.newFixedThreadPool(5);
  18.             // 1) запуск задачи типа Runnable, используем лямбда выражение
  19.             Runnable r = () -> {System.out.println("do something...");};
  20.             executor.submit(r);
  21.             executor.submit(new MyTask());
  22.             // ожидаем некоторое время для выполнения задач
  23.             TimeUnit.SECONDS.sleep(2);
  24.             // прекраащем выполнение пула потоков
  25.             executor.shutdownNow(); // shutdownNow - принудительное завершение
  26.             //executor.shutdown();  // shutdown-ожидаем завершения, новые задачи запустить уже нельзя
  27.              
  28.         } catch (InterruptedException ex) {
  29.             ex.printStackTrace();
  30.         }        
  31.     }    
  32. }
  33. class MyTask implements Runnable{
  34.     @Override
  35.     public void run() {        
  36.         System.out.println("MyTask.run");
  37.     }                
  38. }
  39.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement