Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package io.github.tdudzik.testproject;
- import java.util.Arrays;
- import java.util.List;
- import java.util.concurrent.CountDownLatch;
- import java.util.concurrent.ExecutorService;
- import java.util.concurrent.Executors;
- class Test {
- // // Nie kończy się
- // public void test() {
- // ExecutorService executorService = Executors.newFixedThreadPool(5);
- // IntStream.range(0, 5).forEach(i -> {
- // executorService.execute(() -> {
- // try {
- // Thread.sleep(1000);
- // System.out.println(i);
- // } catch (InterruptedException e) {
- // e.printStackTrace();
- // }
- // });
- // });
- // }
- // // Myślałem, że nie wypisze tych cyfr ale jednak wypisuje
- // // Teraz problemem jest to, że "THE END" jest na początku a MUSI być na końcu
- // public void test() {
- // ExecutorService executorService = Executors.newFixedThreadPool(5);
- //
- // List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
- // numbers.stream().forEach(i -> {
- // executorService.execute(() -> {
- // try {
- // Thread.sleep(5000);
- // System.out.println(i);
- // } catch (InterruptedException e) {
- // e.printStackTrace();
- // }
- // });
- // });
- //
- // System.out.println("THE END");
- // executorService.shutdown();
- // }
- // Teraz jest ok!!!
- public void test() {
- int n = 5;
- ExecutorService executorService = Executors.newFixedThreadPool(n);
- CountDownLatch countDownLatch = new CountDownLatch(n);
- List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
- numbers.stream().forEach(i -> {
- executorService.execute(() -> {
- try {
- Thread.sleep(5000);
- System.out.println(i);
- countDownLatch.countDown();
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- });
- });
- try {
- countDownLatch.await();
- System.out.println("THE END");
- executorService.shutdown();
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- }
- }
- public class TestProjectApp {
- public static void main(String[] args) {
- Test test = new Test();
- test.test();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment