package savinov_roman_lab_1;

import java.util.concurrent.*;

public class MergeSortThreadExecutor extends MergeSortThreadLess {
    private static final ExecutorService executor = Executors.newCachedThreadPool();
    private static final int THRESHOLD = 1500; // Ограничение для многопоточной обработки

    public static void parallelMergeSort(int[][] array, int left, int right) {
        if (left >= right) return;

        if (right - left < THRESHOLD) {
            mergeSort(array, left, right);
            return;
        }

        int middle = (left + right) / 2;

        System.out.println("Создан поток: " + Thread.currentThread().getName());

        // Запускаем параллельно, но не ждем здесь
        CountDownLatch latch = new CountDownLatch(2);

        executor.execute(() -> {
            parallelMergeSort(array, left, middle);
            latch.countDown();
        });

        executor.execute(() -> {
            parallelMergeSort(array, middle + 1, right);
            latch.countDown();
        });

        try {
            latch.await(); // Ожидание завершения обеих задач перед слиянием
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }

        merge(array, left, middle, right);
    }

    public static void shutdown() {
        executor.shutdown();
        try {
            if (!executor.awaitTermination(60, TimeUnit.SECONDS)) {
                executor.shutdownNow();
            }
        } catch (InterruptedException e) {
            executor.shutdownNow();
        }
    }
}
