Odd even number printing using thread

前端 未结 13 2024
挽巷
挽巷 2020-11-29 08:39

Odd even number printing using thread.Create one thread class, two instance of the thread. One will print the odd number and the other will print the even number.

13条回答
  •  庸人自扰
    2020-11-29 09:17

    I have implemented in such a way, based on the argument, no of threads will be spawned and will the respective no in round robin manner. i.e., If thread count is 3, thread 1 will print 1,4 ...; thread 2 will print 2,5,... and thread 3 will print 3,6...

    public class ThreadSynchronizer
    {
    
        public static void main(String[] args)
        {
        // BASED ON THE ARGUMENT MULTIPLE THREADS WILL BE CREATED AND EACH WILL PRINT ITS RESPECTIVE NO
        // IE, IF THREAD COUNT IS 3, THREAD 1 WILL PRINT 1,4 ..., THREAD2 WILL PRINT 2,5,... AND THREAD3 WILL PRINT 3,6...
        // LIMITED THE DISPLAY TO 1000 NOS
        int threadCnt = Integer.parseInt(args[0]);
    
        ReentrantLock lckArray[] = new ReentrantLock[threadCnt + 1];
    
        for (int i = 0; i < threadCnt + 1; i++)
        {
            ReentrantLock lck = new ReentrantLock();
            lck.lock();
            lckArray[i] = lck;
        }
    
        for (int i = 0; i < threadCnt; i++)
        {
            Thread th = new Thread(new Printer(lckArray, i + 1));
            th.start();
        }
    
        for (int i = 1; i < threadCnt + 1; i++)
        {
            lckArray[i].unlock();
    
            while (!lckArray[i].isLocked())
            {
    
            }
        }
        lckArray[0].unlock();
        }
    }
    
    class Printer implements Runnable
    {
    
        private ReentrantLock[] lckArray;
        private int index;
    
        Printer(ReentrantLock[] lckArray, int startValue)
        {
        this.lckArray = lckArray;
        this.index = startValue;
        }
    
        @Override public void run()
        {
        ReentrantLock prevLock = null;
        int printCounter = index;
    
        for (int counter = 0; printCounter <= 1000; counter++)
        {
            int remCounter = counter % lckArray.length;
            int incCounter = lckArray.length - remCounter;
            int indexPostion = index + incCounter;
            int curElementIndex = indexPostion % lckArray.length;
    
            lckArray[curElementIndex].lock();
            if (prevLock != null)
            prevLock.unlock();
            prevLock = lckArray[curElementIndex];
    
            if (curElementIndex == 0)
            {
            System.out.println("Printed by Thread " + index + " " + printCounter);
            printCounter = printCounter + lckArray.length - 1;
            }
    
        }
    
        if (prevLock != null)
        {
            if (prevLock.isHeldByCurrentThread())
            prevLock.unlock();
        }
    
        }
    
    }
    

提交回复
热议问题