Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

3 Threads Printing numbers in sequence

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        6
T1        7
T2        8
T3        9
...and so on.

Here is the

public class ThreadNumberPrinter {

    Object monitor = new Object();
    AtomicInteger number = new AtomicInteger(1);

    public static void main(String[] args) {
        ThreadNumberPrinter tnp = new ThreadNumberPrinter();
        Thread t1 = new Thread(tnp.new Printer(1, 3));
        Thread t2 = new Thread(tnp.new Printer(2, 3));
        Thread t3 = new Thread(tnp.new Printer(3, 3));

        t3.start();
        t1.start();
        t2.start();
    }

    class Printer implements Runnable {

        int threadId;
        int numOfThreads;

        public Printer(int id, int nubOfThreads) {
            threadId = id;
            this.numOfThreads = nubOfThreads;
        }

        public void run() {
            print();
        }

        private void print() {
            try {
                while (true) {
                    Thread.sleep(1000l);
                    synchronized (monitor) {
                        if (number.get() % numOfThreads != threadId) {
                            monitor.wait();
                        } else {
                            System.out.println("ThreadId [" + threadId
                                    + "] printing -->"
                                    + number.getAndIncrement());
                            monitor.notifyAll();
                        }
                    }
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

       }

   }

But just after 2nd thread runs and prints the number 2, all thread get into wait stage and nothing gets printed. I am not sure where I am doing wrong. Any help would be greatly appreciated.

like image 445
Way2Go Avatar asked Jun 21 '15 11:06

Way2Go


People also ask

How to print numbers in sequence using threads in Java?

While printing numbers in sequence using threads trick is to use modulo division to check which thread can print the number and which threads are to be blocked waiting. Each thread is assigned one of the numbers 0, 1 and 2. Each number is divided by 3 (number of threads), remainder will be any one of these numbers 0, 1 or 2.

How to print number from 1 to 10 in a thread?

The idea is take thread count and print 1 in first thread, print 2 in second thread, print 3 in third thread till 10th thread. The output will contain numbers from 1 to 10 based upon the priorities of the threads.

How to write program for sequence using three threads in Java?

Here is the core logic to write program for sequence using three threads. We will use concept of remainder here. If number%3 == 1 then T1 will print the number and increment it else will go in the wait state. If number%3 == 2 then T2 will print the number and increment it else will go in the wait state.

How to synchronize N number of threads using pthread standard library?

Now the task is to synchronize n number of threads using pthread standard library present with gcc compiler. The idea is take thread count and print 1 in first thread, print 2 in second thread, print 3 in third thread till 10th thread. The output will contain numbers from 1 to 10 based upon the priorities of the threads.


Video Answer


1 Answers

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.

like image 189
akhil_mittal Avatar answered Sep 28 '22 23:09

akhil_mittal