• 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
  • Tim Cooke
  • Liutauras Vilda
  • Jeanne Boyarsky
  • paul wheaton
Sheriffs:
  • Ron McLeod
  • Devaka Cooray
  • Henry Wong
Saloon Keepers:
  • Tim Holloway
  • Stephan van Hulst
  • Carey Brown
  • Tim Moores
  • Mikalai Zaikin
Bartenders:
  • Frits Walraven

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
 
Do not meddle in the affairs of dragons - for you are crunchy and good with ketchup. Crunchy tiny ad:
Gift giving made easy with the permaculture playing cards
https://coderanch.com/t/777758/Gift-giving-easy-permaculture-playing
reply
    Bookmark Topic Watch Topic
  • New Topic