Выведите числа 1,2,3, используя нить 1 и 4,5,6, используя нить 2, и 7,8,9, используя нить 3, и снова 10,11,12, используя нить 1 - PullRequest
0 голосов
/ 26 мая 2019

Я пытаюсь написать простую программу с ожиданием и уведомлением, в которой я создам 3 потока.

Первая нить должна печатать 1, 2, 3.

Второй поток должен печатать 4, 5, 6.

Третья нить должна печатать 7, 8, 9.

После этого первая нить должна напечатать 10, 11, 12 и т. Д.

Ниже приведен пример кода для того же упражнения, но я не могу напечатать нужный вывод.

public class MyThread2 extends Thread {

    public final static Object obj = new Object();

    int threadNo;   
    static volatile int threadNoToRun;
    static volatile int counter = 1;

    public MyThread2(int threadNo){
        this.threadNo= threadNo;
    }

    @Override
    public void run() {
        synchronized (obj) {
                try {
                    if(threadNoToRun != threadNo)
                        obj.wait();
                    else{
                        for(int i = 1 ; i < 4 ; i++){
                            if(threadNoToRun == threadNo){
                                System.out.println(threadNo + " counter value is "+counter);
                                counter++;
                                System.out.println(threadNo + " counter value is "+counter);
                                counter++;
                                System.out.println(threadNo + " counter value is "+counter);
                                counter++;
                                if(threadNoToRun == 1){
                                    threadNoToRun = 2;
                                }
                                else if(threadNoToRun == 2){
                                    threadNoToRun = 3;
                                }
                                else if(threadNoToRun == 3){
                                    threadNoToRun = 1;
                                }
                            }
                        }

                        obj.notifyAll();                            
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

        }    
    }

    public static void main (String args[]) {

        /*
         * Creating as many threads as needed.
         */
        MyThread2 th1 = new MyThread2(1);
        MyThread2 th2 = new MyThread2(2);
        MyThread2 th3 = new MyThread2(3);
        MyThread2.threadNoToRun = 1;
        th1.start();
        th2.start();
        th3.start();
    }
}

Вывод выглядит так:

1 counter value is 1
1 counter value is 2
1 counter value is 3
2 counter value is 4
2 counter value is 5
2 counter value is 6

1 Ответ

2 голосов
/ 26 мая 2019

Здесь было всего несколько изменений.

Тем не менее, я должен отметить, что этот тип параллелизма НЕ увеличивает скорость вычислений.Только один поток жив во все времена.

public class MyThread2 extends Thread {

    public final static Object obj = new Object();

    int threadNo;
    static volatile int threadNoToRun;
    static volatile int counter = 1;

    public MyThread2(int threadNo) {
        this.threadNo = threadNo;
    }

    @Override
    public void run() {
        synchronized (obj) {
            try {
                while (counter < 100) {
                    if (threadNoToRun != threadNo)
                        obj.wait();
                    else {
                        System.out.println(threadNo + " counter value is " + counter);
                        counter++;
                        System.out.println(threadNo + " counter value is " + counter);
                        counter++;
                        System.out.println(threadNo + " counter value is " + counter);
                        counter++;
                        if (threadNoToRun == 1) {
                            threadNoToRun = 2;
                        } else if (threadNoToRun == 2) {
                            threadNoToRun = 3;
                        } else if (threadNoToRun == 3) {
                            threadNoToRun = 1;
                        }

                        obj.notifyAll();
                    }
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String args[]) {

        /*
         * Creating as many threads as needed.
         */
        MyThread2 th1 = new MyThread2(1);
        MyThread2 th2 = new MyThread2(2);
        MyThread2 th3 = new MyThread2(3);
        MyThread2.threadNoToRun = 1;
        th1.start();
        th2.start();
        th3.start();
    }
}
...