Задать вопрос

Как синхронизировать потоки в Java?

Здравствуйте, есть задание создать конвейер, где каждый рабочий это 1 поток. Нужно сделать так чтобы потоки обрабатывали предметы. Написал вот такой код, но он очень не стабильный. Выдает правильный результат через некоторое кол-во запусков. Посоветуйте, что можно сделать (sleep нельзя использовать)
spoiler
public class Worker extends Thread{

    private int id;
    private static int itemCounter;
    private int current = 1;
    private static Worker[] workers;
    private boolean done = false;

    private Worker(String name, int id) {
        setName(name);
        this.id = id;
    }

    @Override
    public void run() {

        try {

            if (id != 0) {
                synchronized (this) {

                    wait();
                }
            }

            while (current <= itemCounter) {
                synchronized (this) {



                    System.out.println(Thread.currentThread().getName() + " processing " + current + " item");
                    current++;
                }

                if (id < (workers.length - 1)) {
                    synchronized (workers[id + 1]) {


                        workers[id + 1].notify();
                    }
                }

                if (id > 0) {
                    synchronized (workers[id - 1]) {


                        workers[id - 1].notify();
                    }
                }


                synchronized (this) {

//\\                    try {
//                        for ( int i = 1 ; i < workers.length ; i++ ) {
//
//                            workers[ i ].wait( );
//                        }
//                    } catch ( Exception e ){
//
//                    }



                    if (workers.length != 1) {
                        if (id == (workers.length - 1) && workers[id - 1].done) {
                            continue;
                        }
                        if (current > itemCounter) {
                            done = true;
                            break;
                        }

                        wait();

                    }
                }

            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        int workerCounter = 0;
        if (args.length != 2) {
            System.err.println("Error, use two arguments!");
            throw new Error();

        } else {
            try {
                workerCounter = Integer.parseInt(args[0]);
                itemCounter = Integer.parseInt(args[1]);
                if (workerCounter <= 0 || itemCounter <= 0) {
                    throw new Exception();
                }
            } catch (Exception e) {
                System.err.println("Error: Invalid args.");
                System.exit(1);
            }

            System.out.println(workerCounter + " Workers; " + itemCounter + " Items");

            workers = new Worker[workerCounter];
            for (int i = 0; i < workers.length; i++) {

                workers[i] = new Worker("Worker" + (i + 1), i);
            }

            for (int i = 1; i < workers.length; i++) {

                workers[i].start();
            }
            workers[0].start();
        }
    }
}
spoiler
4 Workers; 50 Items
Worker1 processing 1 item
Worker2 processing 1 item
Worker1 processing 2 item
Worker3 processing 1 item
Worker2 processing 2 item
Worker4 processing 1 item
Worker1 processing 3 item
Worker3 processing 2 item
Worker2 processing 3 item
Worker4 processing 2 item
Worker1 processing 4 item
Worker3 processing 3 item
Worker2 processing 4 item
Worker4 processing 3 item
Worker1 processing 5 item
Worker3 processing 4 item
Worker2 processing 5 item
Worker4 processing 4 item
Worker1 processing 6 item
Worker3 processing 5 item
Worker2 processing 6 item
Worker4 processing 5 item
Worker1 processing 7 item
Worker3 processing 6 item
Worker2 processing 7 item
Worker4 processing 6 item
Worker1 processing 8 item
Worker3 processing 7 item
Worker2 processing 8 item
Worker4 processing 7 item
Worker1 processing 9 item
Worker3 processing 8 item
Worker2 processing 9 item
Worker4 processing 8 item
Worker1 processing 10 item
Worker2 processing 10 item
Worker3 processing 9 item
Worker4 processing 9 item
Worker1 processing 11 item
Worker3 processing 10 item
Worker2 processing 11 item
Worker4 processing 10 item
Worker1 processing 12 item
Worker3 processing 11 item
Worker2 processing 12 item
Worker4 processing 11 item
Worker1 processing 13 item
Worker3 processing 12 item
Worker2 processing 13 item
Worker4 processing 12 item
Worker1 processing 14 item
Worker3 processing 13 item
Worker2 processing 14 item
Worker4 processing 13 item
Worker1 processing 15 item
Worker3 processing 14 item
Worker2 processing 15 item
Worker4 processing 14 item
Worker2 processing 16 item
Worker1 processing 16 item
Worker3 processing 15 item
Worker1 processing 17 item
Worker4 processing 15 item
Worker2 processing 17 item
Worker3 processing 16 item
Worker4 processing 16 item
Worker1 processing 18 item
Worker3 processing 17 item
Worker2 processing 18 item
Worker1 processing 19 item
Worker2 processing 19 item
Worker3 processing 18 item
Worker4 processing 17 item
Worker3 processing 19 item
Worker2 processing 20 item
Worker4 processing 18 item
Worker1 processing 20 item
Worker2 processing 21 item
Worker3 processing 20 item
Worker1 processing 21 item
Worker4 processing 19 item
Worker2 processing 22 item
Worker3 processing 21 item
Worker4 processing 20 item
Worker1 processing 22 item
Worker3 processing 22 item
Worker2 processing 23 item
Worker4 processing 21 item
Worker1 processing 23 item
Worker3 processing 23 item
Worker2 processing 24 item
Worker4 processing 22 item
Worker2 processing 25 item
Worker1 processing 24 item
Worker3 processing 24 item
Worker4 processing 23 item
Worker1 processing 25 item
Worker3 processing 25 item
Worker2 processing 26 item
Worker4 processing 24 item
Worker1 processing 26 item
Worker3 processing 26 item
Worker2 processing 27 item
Worker4 processing 25 item
Worker1 processing 27 item
Worker3 processing 27 item
Worker2 processing 28 item
Worker4 processing 26 item
Worker2 processing 29 item
Worker1 processing 28 item
Worker3 processing 28 item
Worker1 processing 29 item
Worker4 processing 27 item
Worker2 processing 30 item
Worker3 processing 29 item
Worker4 processing 28 item
Worker1 processing 30 item
Worker3 processing 30 item
Worker2 processing 31 item
Worker4 processing 29 item
Worker1 processing 31 item
Worker3 processing 31 item
Worker2 processing 32 item
Worker4 processing 30 item
Worker1 processing 32 item
Worker3 processing 32 item
Worker2 processing 33 item
Worker4 processing 31 item
Worker1 processing 33 item
Worker3 processing 33 item
Worker2 processing 34 item
Worker4 processing 32 item
Worker1 processing 34 item
Worker3 processing 34 item
Worker2 processing 35 item
Worker4 processing 33 item
Worker1 processing 35 item
Worker3 processing 35 item
Worker2 processing 36 item
Worker4 processing 34 item
Worker1 processing 36 item
Worker3 processing 36 item
Worker2 processing 37 item
Worker4 processing 35 item
Worker1 processing 37 item
Worker3 processing 37 item
Worker2 processing 38 item
Worker4 processing 36 item
Worker2 processing 39 item
Worker1 processing 38 item
Worker3 processing 38 item
Worker4 processing 37 item
Worker1 processing 39 item
Worker3 processing 39 item
Worker2 processing 40 item
Worker4 processing 38 item
Worker1 processing 40 item
Worker3 processing 40 item
Worker2 processing 41 item
Worker4 processing 39 item
Worker1 processing 41 item
Worker3 processing 41 item
Worker2 processing 42 item
Worker4 processing 40 item
Worker2 processing 43 item
Worker1 processing 42 item
Worker3 processing 42 item
Worker1 processing 43 item
Worker4 processing 41 item
Worker2 processing 44 item
Worker3 processing 43 item
Worker4 processing 42 item
Worker1 processing 44 item
Worker3 processing 44 item
Worker2 processing 45 item
Worker4 processing 43 item
Worker1 processing 45 item
Worker2 processing 46 item
Worker3 processing 45 item
Worker4 processing 44 item
Worker1 processing 46 item
Worker3 processing 46 item
Worker2 processing 47 item
Worker4 processing 45 item
Worker2 processing 48 item
Worker1 processing 47 item
Worker3 processing 47 item
Worker1 processing 48 item
Worker4 processing 46 item
Worker2 processing 49 item
Worker3 processing 48 item
Worker1 processing 49 item
Worker4 processing 47 item
Worker2 processing 50 item
Worker3 processing 49 item
Worker1 processing 50 item
Worker4 processing 48 item
Worker3 processing 50 item
Worker4 processing 49 item
Worker4 processing 50 item
  • Вопрос задан
  • 144 просмотра
Подписаться 3 Простой 2 комментария
Пригласить эксперта
Ответы на вопрос 1
LaRN
@LaRN
Senior Developer
Похожий вопрос разбирали вот тут.
Чем отличается семафор, мьютекс и монитор? Или это одно и тоже?

И более подробно здесь
https://habrahabr.ru/post/277669/
Ответ написан
Комментировать
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Похожие вопросы