суббота, 18 апреля 2020 г.

Пул потоков Thread pool

import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;import java.util.concurrent.TimeUnit;
public class pool {
    public static void main(String[] args) {
        ExecutorService executorService = Executors.newFixedThreadPool(3);        for (int i = 0; i < 5; i++) {
            executorService.submit(new work(i));        }
        executorService.shutdown();        try {
            executorService.awaitTermination(1, TimeUnit.DAYS);        } catch (InterruptedException e) {
            e.printStackTrace();        }
    }
}
class work implements Runnable{
    private int id;    public work(int id) {
        this.id = id;    }
    @Override    public void run() {
        try {
            Thread.sleep(5000);        } catch (InterruptedException e) {
            e.printStackTrace();        }
        System.out.println("Work with id = " + id + " finished.");    }
}