3 Threads Printing numbers in sequence

前端 未结 14 1338
不思量自难忘°
不思量自难忘° 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:12

    public class PrintThreadsSequentially {
    
    static int number = 1;
    static final int PRINT_NUMBERS_UPTO = 20;
    static Object lock = new Object();
    
    static class SequentialThread extends Thread {
        int remainder = 0;
        int noOfThreads = 0;
    
        public SequentialThread(String name, int remainder, int noOfThreads) {
            super(name);
            this.remainder = remainder;
            this.noOfThreads = noOfThreads;
        }
    
        @Override
        public void run() {
            while (number < PRINT_NUMBERS_UPTO) {
                synchronized (lock) {
                    while (number % noOfThreads != remainder) { // wait for numbers other than remainder
                        try {
                            lock.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                    System.out.println(getName() + " value " + number);
                    number++;
                    lock.notifyAll();
                }
            }
        }
    }
    
    public static void main(String[] args) {
        SequentialThread first = new SequentialThread("First Thread", 0, 4);
        SequentialThread second = new SequentialThread("Second Thread", 1, 4);
        SequentialThread third = new SequentialThread("Third Thread", 2, 4);
        SequentialThread fourth = new SequentialThread("Fourth Thread", 3, 4);
        first.start();  second.start();   third.start();  fourth.start();
    }
    

    }

提交回复
热议问题