3 Threads Printing numbers in sequence

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

    Though this is a bad way for using threads, if we still want it a generic solution can be to have a worker thread which will store its id:

    class Worker extends Thread {
        private final ResourceLock resourceLock;
        private final int threadNumber;
        private final AtomicInteger counter;
        private volatile boolean running = true;
        public Worker(ResourceLock resourceLock, int threadNumber, AtomicInteger counter) {
            this.resourceLock = resourceLock;
            this.threadNumber = threadNumber;
            this.counter = counter;
        }
        @Override
        public void run() {
            while (running) {
                try {
                    synchronized (resourceLock) {
                        while (resourceLock.flag != threadNumber) {
                            resourceLock.wait();
                        }
                        System.out.println("Thread:" + threadNumber + " value: " + counter.incrementAndGet());
                        Thread.sleep(1000);
                        resourceLock.flag = (threadNumber + 1) % resourceLock.threadsCount;
                        resourceLock.notifyAll();
                    }
                } catch (Exception e) {
                    System.out.println("Exception: " + e);
                }
            }
        }
        public void shutdown() {
            running = false;
        }
    }
    

    The ResourceLock class would store flag and max threads count:

    class ResourceLock {
        public volatile int flag;
        public final int threadsCount;
    
        public ResourceLock(int threadsCount) {
            this.flag = 0;
            this.threadsCount = threadsCount;
        }
    }
    

    And then main class can use it as below:

    public static void main(String[] args) throws InterruptedException {
            final int threadsCount = 3;
            final ResourceLock lock = new ResourceLock(threadsCount);
            Worker[] threads = new Worker[threadsCount];
            final AtomicInteger counter = new AtomicInteger(0);
            for(int i=0; i<threadsCount; i++) {
                threads[i] = new Worker(lock, i, counter);
                threads[i].start();
            }
            Thread.sleep(10000);
            System.out.println("Will try to shutdown now...");
            for(Worker worker: threads) {
                worker.shutdown();
            }
        }
    

    Here after a certain delay we may like to stop the count and the method shutdown in worker provides this provision.

    0 讨论(0)
  • 2021-02-06 00:07

    Bad way to do but ask is to implement using multiple threads:

    private static AtomicInteger currentThreadNo = new AtomicInteger(0);
        private static int currentNo = 1;
        private static final Object lock = new Object();
    

    Above, these values are static so that they remain same for all the worker objects.

    import java.util.concurrent.atomic.AtomicInteger;
    
    public class PrintNumbersUsingNThreads implements Runnable {
    
        private final int threadNo;
        private final int totalThreads;
        private static AtomicInteger currentThreadNo = new AtomicInteger(0);
        private static int currentNo = 1;
        private static final Object lock = new Object();
    
    
        public PrintNumbersUsingNThreads(int threadNo, int totalThreads) {
            this.threadNo = threadNo;
            this.totalThreads = totalThreads;
        }
    
        @Override
        public  void run() {
    
    
    
            while (true) {
                while (currentThreadNo.get() % totalThreads != threadNo) {
                    try {
    
                        synchronized (lock) {
                            lock.wait();
                        }
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                System.out.println(Thread.currentThread().getName() + " printing " + currentNo);
                currentNo++;
    
                int curr = currentThreadNo.get();
                if (curr == totalThreads) {
                    currentThreadNo.set(1);
                } else {
                   currentThreadNo.incrementAndGet();
                }
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                synchronized (lock) {
                    lock.notifyAll();
                }
            }
    
        }
    
        public static void main(String[] args) {
            int totalThreads = 3;
    
            for(int i = 0; i < totalThreads; i++){
                new Thread(new PrintNumbersUsingNThreads(i,totalThreads),"thread"+i).start();
            }
    
        }
    }
    

    output:

    thread0 printing 1
    thread1 printing 2
    thread2 printing 3
    thread0 printing 4
    thread1 printing 5
    thread2 printing 6
    thread0 printing 7
    thread1 printing 8
    thread2 printing 9
    thread0 printing 10
    thread1 printing 11
    thread2 printing 12
    thread0 printing 13
    thread1 printing 14
    thread2 printing 15
    thread0 printing 16
    thread1 printing 17
    thread2 printing 18
    
    0 讨论(0)
  • 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();
    }
    

    }

    0 讨论(0)
  • 2021-02-06 00:14

    The ThreadSynchronization class can be used to print numbers between 'n' no. of threads in sequence. The logic is to create a common object between each of the consecutive threads and use 'wait', 'notify' to print the numbers in sequence. Note: Last thread will share an object with the first thread.

    You can change the 'maxThreads' value to increase or decrease the number of thread in the program before running it.

    import java.util.ArrayList;
    import java.util.List;
    
    public class ThreadSynchronization {
    
        public static int i = 1;
        public static final int maxThreads = 10;
    
        public static void main(String[] args) {
            List<Object> list = new ArrayList<>();
            for (int i = 0; i < maxThreads; i++) {
                list.add(new Object());
            }
            Object currObject = list.get(maxThreads - 1);
            for (int i = 0; i < maxThreads; i++) {
                Object nextObject = list.get(i);
                RunnableClass1 a = new RunnableClass1(currObject, nextObject, i == 0 ? true : false);
                Thread th = new Thread(a);
                th.setName("Thread - " + (i + 1));
                th.start();
                currObject = list.get(i);
            }
        }
    
    }
    
    class RunnableClass implements Runnable {
    
        private Object currObject;
        private Object nextObject;
        private boolean firstThread;
    
        public RunnableClass(Object currObject, Object nextObject, boolean first) {
            this.currObject = currObject;
            this.nextObject = nextObject;
            this.firstThread = first;
        }
    
        @Override
        public void run() {
            int i = 0;
            try {
                if (firstThread) {
                    Thread.sleep(5000);
                    firstThread = false;
                    System.out.println(Thread.currentThread().getName() + " - " + ThreadSynchronization.i++);
                    synchronized (nextObject) {
                        nextObject.notify();
                    }
                }
                while (i++ < Integer.MAX_VALUE) {
                    synchronized (currObject) {
                        currObject.wait();
                    }
                    System.out.println(Thread.currentThread().getName() + " - " + ThreadSynchronization.i++);
                    Thread.sleep(1000);
                    synchronized (nextObject) {
                        nextObject.notify();
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
    
    0 讨论(0)
  • 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();
        }
    
    }
    
    0 讨论(0)
  • 2021-02-06 00:15

    How about this?

    public class PrintNumbers implements Runnable {
    
        public static final int NO_OF_THREADS = 3;
        public static final int MAX_DIGIT = 20;
        public static final String THREAD_NAME_PREFIX = "t";
    
        volatile int current = 1;
        private Object lock = new Object();
    
        public static void main(String[] args) {
            PrintNumbers printNumbers = new PrintNumbers();
            for (int i = 1; i <= NO_OF_THREADS; i++) {
                new Thread(printNumbers, THREAD_NAME_PREFIX + i).start();
            }
        }
    
        @Override
        public void run() {
            String printThread;
            while (current < MAX_DIGIT) {
                synchronized (lock) {
                    if (current % NO_OF_THREADS != 0) {
                        printThread = THREAD_NAME_PREFIX + current % NO_OF_THREADS;
                    } else {
                        printThread = THREAD_NAME_PREFIX + NO_OF_THREADS;
                    }
    
                    if (!printThread.equals(Thread.currentThread().getName())) {
                        try {
                            lock.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
    
                    if (printThread.equals(Thread.currentThread().getName())) {
                        System.out.println(String.format("Thread %s : %s", Thread.currentThread().getName(), current));
                        current = current + 1;
                    }
    
                    lock.notifyAll();
                }
            }
        }
    }
    
    0 讨论(0)
提交回复
热议问题