0

I'm using java8 & I wrote a program to identify the behaviour of 'Synchronized()' of Threads in java.These are the classes I've created & I got unexpected output.

public class PrintNumberDemo {

public void printNumbers() {
    for(int i=0;i<=20;i++) {
        System.out.println(i);
    }
}

}

public class PrintStarDemo {
public void printStars() {
    for(int i=0;i<=20;i++) {
        System.out.println("*");
    }
}

}

public class PrintThread implements Runnable {

Thread t;
String name;
PrintNumberDemo pd;
PrintStarDemo ps;

PrintThread(Object ob, String name) {
    if (ob instanceof PrintNumberDemo) {
        this.pd = (PrintNumberDemo) ob;
    }
    if (ob instanceof PrintStarDemo) {
        this.ps = (PrintStarDemo) ob;
    }
    this.name = name;
}

@Override
public void run() {
    // TODO Auto-generated method stub
    if (pd != null)
        synchronized (pd) {
            pd.printNumbers();
        }
    if (ps != null)
        synchronized (ps) {
            ps.printStars();
        }

}

public void start() {
    if (t == null) {
        t = new Thread(this, name);
        System.out.println("Starting " + name);
        t.start();
    }

}

}

public class TestPrintDemo {

public static void main(String[] args) {

    PrintNumberDemo pd1= new PrintNumberDemo();
    PrintStarDemo ps1 = new PrintStarDemo();

    PrintThread t1 = new PrintThread(pd1,"Thread-01");      
    PrintThread t2 = new PrintThread(ps1,"Thread-02");
    t1.start();
    t2.start();
}

}

Output:

Starting Thread-01 Starting Thread-02 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
* 17 18 19 20

Anybody can explain, why it displys such output?

chk.buddi
  • 554
  • 1
  • 8
  • 29
  • What did you expect? – GhostCat Sep 17 '17 at 10:08
  • I expected the following output : Starting Thread-01 Starting Thread-02 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 * * * * * * * * * * * * * * * * * * * * * – chk.buddi Sep 17 '17 at 10:18
  • The observed output is independent of your choice to synchronize the print statements, because there is no conflicting call to that code. The first thread is interrupted at a random time (here after printing 16) and the second thread outputs some stars. As it happens it outputs all of them, Afterwards thread 1 continues. – Stefan Sep 17 '17 at 10:26

0 Answers0