0

Задача: необходимо реализовать многопоточную обработку массива дат при помощи массива из M потоков, используя для синхронизации объект ядра – семафор.

public class ArrayThreadsWithSemaphore {
    private ArrayList<WorkerFromDay> arrayThreads = new ArrayList<>();
    public DateRange dateCollection;
    public ArrayList<LocalDate> collection;
    public int selectedDay, countThreadsFromDayWork, quant, count;
    public ArrayThreadsWithSemaphore(DateRange dateCollection, int selectedDay, int countThreadsFromDayWork, int quant) {
        this.dateCollection = dateCollection;
        this.selectedDay = selectedDay;
        this.countThreadsFromDayWork = countThreadsFromDayWork;
        this.quant = quant;
    }
  
    public void schedule() throws InterruptedException {
        //индекс массива
        count = 0;
        //коллекция дат
        collection = new ArrayList(dateCollection.toList().size());
        collection.addAll(dateCollection.toList());
        Semaphore semaphore = new Semaphore(1); //семафор 1 разрешение
        //запуск потоков
        for (int i = 0; i < countThreadsFromDayWork; i++) {
            WorkerFromDay worker = new WorkerFromDay(semaphore);
            worker.setName("Поток-" + i);
            arrayThreads.add(worker);
            worker.start();
        }
        //ждем пока вся работа не выполнится
        while (count < dateCollection.toList().size()){}
        printResult();
    }

    public void printResult(){//вывод результатов
        long timeAlgoritm = 0;
        System.out.println("Результат работы многопоточного алгоритма:");
        for (WorkerFromDay thread : arrayThreads) {
            if (thread.getWorkTimeThread() > timeAlgoritm) {
                timeAlgoritm = thread.getWorkTimeThread();
            }
            if (thread.getLogWorker().isEmpty()) {
                System.out.println(thread.getName() + " Не нашел подходящих дат");
            } else System.out.println(thread.getName() + " определил что: " + thread.getLogWorker());
        }
        System.out.println("Время работы многопоточного алгоритма: " + timeAlgoritm + "\n");
    }

    public class WorkerFromDay extends Thread {
        private long startTimeThread, workTimeThread;//время начала и конца работы
        public ArrayList<String> logWorker = new ArrayList<>();//лог работы
        private Semaphore semaphore;

        public WorkerFromDay(Semaphore semaphore) {
            this.startTimeThread = System.currentTimeMillis();
            this.workTimeThread = System.currentTimeMillis();
            this.semaphore = semaphore;
        }

        public ArrayList<String> getLogWorker() {
            return logWorker;
        }

        public long getWorkTimeThread() {
            return workTimeThread;
        }

        @Override
        public void run() {
            try {
                LocalDate currentDay = null;
                startTimeThread = System.currentTimeMillis();
                while (!isInterrupted()) {
                    semaphore.acquire();
                    if (count >= collection.size() - 1) {
                        semaphore.release();
                        interrupt();
                    } else {
                        count++;
                        currentDay = collection.get(count);
                        semaphore.release();
                    }
                    if (currentDay.getDayOfWeek().getValue() == selectedDay) {
                        logWorker.add( currentDay + " выпадает на " + currentDay.getDayOfWeek().toString());
                    }
                    sleep(quant);//имитация работы
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                workTimeThread = System.currentTimeMillis() - startTimeThread;
            }
        }
    }
}

Выдает ошибку:

java.lang.InterruptedException: sleep interrupted
    at java.base/java.lang.Thread.sleep(Native Method)
    at com.tusur.parallel/com.tusur.parallel.ArrayThreadsWithSemaphore$WorkerFromDay.run(ArrayThreadsWithSemaphore.java:116)
java.lang.InterruptedException: sleep interrupted
    at java.base/java.lang.Thread.sleep(Native Method)
    at com.tusur.parallel/com.tusur.parallel.ArrayThreadsWithSemaphore$WorkerFromDay.run(ArrayThreadsWithSemaphore.java:116)
java.lang.InterruptedException: sleep interrupted
    at java.base/java.lang.Thread.sleep(Native Method)
    at com.tusur.parallel/com.tusur.parallel.ArrayThreadsWithSemaphore$WorkerFromDay.run(ArrayThreadsWithSemaphore.java:116)

1 ответ 1

0

Ошибка была в неверном положении вызова метода прерывания и семафоров. Так все работает:

public class WorkerFromDay extends Thread {
        private long workTimeThread;//время конца работы
        public ArrayList<String> logWorker = new ArrayList<>();//лог работы
        private Semaphore semaphore;

        public WorkerFromDay(Semaphore semaphore) {
            this.semaphore = semaphore;
        }

        @Override
        public void run() {
            try {
                LocalDate currentDay = null;
                long startTimeThread = System.currentTimeMillis();
                while (true) {
                    semaphore.acquire();
                    if (count < collection.size()) {
                        currentDay = collection.get(count);
                        count++;
                    } else {
                        semaphore.release();
                        break;
                    }
                    semaphore.release();
                    if (currentDay.getDayOfWeek().getValue() == selectedDay) {
                        logWorker.add( currentDay + " выпадает на " + currentDay.getDayOfWeek().toString());
                    }
                    sleep(quant);//имитация работы
                }
                workTimeThread = System.currentTimeMillis() - startTimeThread;
                Thread.currentThread().interrupt();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

Ваш ответ

Нажимая на кнопку «Отправить ответ», вы соглашаетесь с нашими условиями использования и подтверждаете, что прочитали и поняли наши политику конфиденциальности и нормы поведения.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.