My understanding of monitors , and hence the use of
word 'synchronized'is that when a
thread acquires the monitor of an object or class , it will block out all the other threads ..
I fave two classes with code like this :
<code>
public class multiThread1 implements Runnable {
String str;
public static checkThreads ck;
public multiThread1(String str) {
this.str= str;
}
public static void main(String arg[]){
multiThread1 mt1 = new multiThread1("Thread1");
multiThread1 mt2 = new multiThread1("Thread2");
ck = new checkThreads();
Thread t1 = new Thread(mt1);
Thread t2 = new Thread(mt2);
t1.start();
t2.start();
}
public void run(){
doIteration(str);
}
public void doIteration(String str){
for(int x=0;x<5;x++){
ck.threading(str,x);
}
}
}
</code>
and another class : with a synchronised method..
<code>
public class checkThreads
{
public synchronized void threading(String str,int time) {
System.out.println("from 0: "+time +" "+ str );
}
}
</code>
when I ran multiThread1 , I was expecting an output of :
Thread1
Thread1
Thread1
Thread1
Thread1
Thread2
Thread2
Thread2
Thread2
Thread2
But the output was observed to have a mix of Thread1 and Thread2 , interleaved .Not a block of 'Thread1's and then 'Thread2's as I expected .
How is it explained ?
[This message has been edited by Anirban Chatterjee (edited October 27, 2001).]