3 Threads Printing numbers in sequence

前端 未结 14 1369
不思量自难忘°
不思量自难忘° 2021-02-05 23:45

I am trying to write a simple code to print numbers in sequence. Scenario is like

Thread  Number
T1        1
T2        2
T3        3
T1        4
T2        5
T3          


        
14条回答
  •  情深已故
    2021-02-06 00:04

      public class TestClass {
    
        private volatile Integer count = 1;
        private volatile Integer threadIdToRun = 1;
        private Object object = new Object();
    
        public static void main(String[] args) {
    
            TestClass testClass = new TestClass();
            Thread t1 = new Thread(testClass.new Printer(1));
            Thread t2 = new Thread(testClass.new Printer(2));
            Thread t3 = new Thread(testClass.new Printer(3));
    
            t1.start();
            t2.start();
            t3.start();
        }
    
        class Printer implements Runnable {
    
            private int threadId;
    
            public Printer(int threadId) {
                super();
                this.threadId = threadId;
            }
    
            @Override
            public void run() {
                try {
                    while (count <= 20) {
                        synchronized (object) {
                            if (threadId != threadIdToRun) {
                                object.wait();
                            } else {
                                System.out.println("Thread " + threadId + " printed " + count);
                                count += 1;
    
                                if (threadId == 1)
                                    threadIdToRun = 2;
                                else if (threadId == 2)
                                    threadIdToRun = 3;
                                else if (threadId == 3)
                                    threadIdToRun = 1;
    
                                object.notifyAll();
                            }
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
    
            }
        }
    }
    

    Above program gives output

    Thread 1 printed 1
    Thread 2 printed 2
    Thread 3 printed 3
    Thread 1 printed 4
    Thread 2 printed 5
    Thread 3 printed 6
    Thread 1 printed 7
    Thread 2 printed 8
    Thread 3 printed 9
    Thread 1 printed 10
    Thread 2 printed 11
    Thread 3 printed 12
    Thread 1 printed 13
    Thread 2 printed 14
    Thread 3 printed 15
    Thread 1 printed 16
    Thread 2 printed 17
    Thread 3 printed 18
    Thread 1 printed 19
    Thread 2 printed 20
    

提交回复
热议问题