• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

problem with monitors :

 
Greenhorn
Posts: 18
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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).]
 
author
Posts: 3252
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
 
reply
    Bookmark Topic Watch Topic
  • New Topic