• Post Reply Bookmark Topic Watch Topic
  • New Topic

problem with monitors :  RSS feed

 
Anirban Chatterjee
Greenhorn
Posts: 18
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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).]
 
Peter den Haan
author
Ranch Hand
Posts: 3252
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Synchronization works only within the synchronized block or method - the moment you're leaving the method, you give up your monitor lock and other threads can get in. So, although only one of your threads will be executing the "threading()" method at any given time, they both get a go at executing it in turn.
- Peter
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!