Home > Software engineering >  java 2 Threads Printing numbers in sequence
java 2 Threads Printing numbers in sequence

Time:09-16

I'm trying to print 1 to 10 in sequence using 2 threads.

Here is the code.

public class Multithreading implements Runnable {
    private static volatile Integer count = 1;
    private static volatile String threadId = "1";

    Object object = new Object();
    @Override
    public void run() {
        try {
            while (count <= 10) {
                synchronized (object) {
                    if(!Thread.currentThread().getName().equals(threadId)) {
                        object.wait();
                    }
                    else {
                        System.out.println(Thread.currentThread().getName() " "  count);
                        count  ;
                        if(threadId.equals("1"))
                            threadId = "2";
                        else threadId = "1";
                        object.notifyAll();
                    }
                }
            }
        }
        catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        Multithreading t1m = new Multithreading();
        Multithreading t2m = new Multithreading();
        Thread t1 = new Thread(t1m);
        Thread t2 = new Thread(t2m);

        t1.setName("1");
        t2.setName("2");
        t1.start();
        t2.start();
    }
}

But both threads are going to wait after printing 1st thread prints 1.

I'm trying to implement this 3 Threads Printing numbers in sequence solution for two threads without a nested inner class. Any help would be greatly appreciated.

CodePudding user response:

The object variable is a member variable. Each instance of your Multithreading class is creating, synchronizing on, waiting for, and notifying its own distinct object. Maybe you meant for object to be a static variable?


Edit:

In the question you cited, the monitor variable is a member variable—just like your object—but the code creates only one instance of the class in which monitor appears. All the threads share the same monitor. The same is true of the object variable in the most highly upvoted answer to that question. All the threads share the same object in that answer.

The way in which you got rid of the inner class from those examples causes each thread to have its own, separate object.

  • Related