Synchronization works correctly in this code:
class PrintNumbers {
synchronized public void display() {
System.out.println("in display");
for (int i = 0; i < 3; i++) {
System.out.println("Thread name : "+ Thread.currentThread().getName() + " i= " + i);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.getMessage();
}
}
System.out.println("out of display");
}
}
class MyThread implements Runnable {
Thread t;
PrintNumbers printNumbers;
MyThread(PrintNumbers printNumbers, String s) {
this.printNumbers = printNumbers;
t = new Thread(this,s);
t.start();
}
public void run() {
printNumbers.display();
}
}
class SyncExample {
public static void main(String[] args) {
PrintNumbers printNumbers = new PrintNumbers();
new MyThread(printNumbers, "My Thread 1");
new MyThread(printNumbers, "My Thread 2");
}
}
Output:
in display
Thread name : My Thread 1 i= 0
Thread name : My Thread 1 i= 1
Thread name : My Thread 1 i= 2
out of display
in display
Thread name : My Thread 2 i= 0
Thread name : My Thread 2 i= 1
Thread name : My Thread 2 i= 2
out of display
but not in this code:
class PrintNumbers {
synchronized public void display() {
System.out.println("in display");
for (int i = 0; i < 3; i++) {
System.out.println("Thread name : "+ Thread.currentThread().getName() + " i= " + i);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.getMessage();
}
}
System.out.println("out of display");
}
}
class MyThread implements Runnable {
Thread t;
PrintNumbers printNumbers;
MyThread(String s) {
this.printNumbers = new PrintNumbers();
t = new Thread(this,s);
t.start();
}
public void run() {
printNumbers.display();
}
}
class SyncExample {
public static void main(String[] args) {
new MyThread("My Thread 1");
new MyThread("My Thread 2");
}
}
Output:
in display
Thread name : My Thread 1 i= 0
in display
Thread name : My Thread 2 i= 0
Thread name : My Thread 1 i= 1
Thread name : My Thread 2 i= 1
Thread name : My Thread 2 i= 2
Thread name : My Thread 1 i= 2
out of display
out of display
I cannot understand what difference wrt Synchronization does it make to initialize PrintNumbers in the Runnable MyThread and in the SyncExample class. Please explain.
this
. – Swaneydisplay
method static , they are locking 2 objects . – Cooperative