3 Threads Printing numbers in sequence

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

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

提交回复
热议问题