Hi,
I am using the example codes Maha Anna posted on line a couple months ago,(Thanks, Maha) and modify it a lot bit( which is added wait()/notify() methods into the synch method) to try to grasp the synch idea. But the output confused me, could anybody explain to me?
Thanks in advance.
This is oraginal codes/output (understand it):
class PrintUpto5 {
//some other code..
synchronized void syncPrint(){
for(int i=0; i<5; i++) {
System.out.println("i= "+i+Thread.currentThread().getName()+" " + "Sysnc print ");
}
}
//some other code....
}
class ThreadCalling_Sync_Method extends
Thread {
PrintUpto5 obj=null;
ThreadCalling_Sync_Method() {
super();
}
ThreadCalling_Sync_Method(PrintUpto5 obj) {
this.obj = obj;
}
public void run() {
this.obj.syncPrint();//Call the Synchronized Method
}
}
class
Test {
public static void main(
String[] args) throws Exception {
//Create the 2 objects of SAME class which will be bumbarded
//by the threads
PrintUpto5 printObj = new PrintUpto5();
PrintUpto5 printObj1 = new PrintUpto5();
//Scenario 1
ThreadCalling_Sync_Method t1 = new ThreadCalling_Sync_Method (printObj);
ThreadCalling_Sync_Method t2 = new ThreadCalling_Sync_Method (printObj);
t1.start();
t2.start();
}
/*-- output Scenario 1-------
i= 0Thread-0 Sysnc print
i= 1Thread-0 Sysnc print
i= 2Thread-0 Sysnc print
i= 3Thread-0 Sysnc print
i= 4Thread-0 Sysnc print
i= 0Thread-1 Sysnc print
i= 1Thread-1 Sysnc print
i= 2Thread-1 Sysnc print
i= 3Thread-1 Sysnc print
i= 4Thread-1 Sysnc print
And this is the only changed I make and what I got( have no idea):
synchronized void syncPrint(){
try{
for(int i=0; i<5; i++){
System.out.println("i= " +i+ Thread.currentThread().getName()+" "+"Sync print
");
wait();
}
} catch(InterruptedException e) {}
notify();
}
/*----------------output---
i= 0Thread-0 Sync print
i= 0Thread-1 Sync print