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?