3 Threads Printing numbers in sequence

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

        package com.sourav.mock.Thread;
    
        import java.util.concurrent.atomic.AtomicInteger;
    
        public class ThreeThreadComunication implements Runnable {
            AtomicInteger counter;
            int[] array;
            static final Object mutex = new Object();
    
            public ThreeThreadComunication(int[] array, AtomicInteger counter){
                this.counter = counter;
                this.array = array;
            }
    
            @Override
            public void run() {
                int i = 0;
                while(i < array.length){
                    synchronized(mutex){
                        if(Integer.parseInt(Thread.currentThread().getName()) == counter.get()){
                            System.out.println(array[i]);
                            if(counter.get() == 3){
                                counter.getAndSet(1);
                            }else{
                                int c = counter.get();
                                counter.getAndSet(++c);
                            }
                            i++;
                        }
    
                        mutex.notifyAll();
                        try {
                            mutex.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        }
    
    package com.sourav.mock.Thread;
    
    import java.util.concurrent.atomic.AtomicInteger;
    
    public class ThreeThreadComunicationTest {
    
        public static void main(String[] args) {
    
            AtomicInteger counter = new AtomicInteger(1);
            int[] array1 = new int[]{1, 4, 7};
            int[] array2 = new int[]{2, 5, 8};
            int[] array3 = new int[]{3, 6, 9};
    
            ThreeThreadComunication obj1 = new ThreeThreadComunication(array1, counter);
            ThreeThreadComunication obj2 = new ThreeThreadComunication(array2, counter);
            ThreeThreadComunication obj3 = new ThreeThreadComunication(array3, counter);
    
            Thread t1 = new Thread(obj1, "1");
            Thread t2 = new Thread(obj2, "2");
            Thread t3 = new Thread(obj3, "3");
    
            t1.start();
            t2.start();
            t3.start();
        }
    
    }
    

提交回复
热议问题