• 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 all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Paul Clapham
  • Ron McLeod
  • Liutauras Vilda
  • Bear Bibeault
Sheriffs:
  • Jeanne Boyarsky
  • Tim Cooke
  • Devaka Cooray
Saloon Keepers:
  • Tim Moores
  • Tim Holloway
  • Piet Souris
  • salvin francis
  • Stephan van Hulst
Bartenders:
  • Frits Walraven
  • Carey Brown
  • Jj Roberts

problem with monitors :

 
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).]
 
author
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
 
We don't have time for this. We've gotta save the moon! Or check this out:
the value of filler advertising in 2020
https://coderanch.com/t/730886/filler-advertising
reply
    Bookmark Topic Watch Topic
  • New Topic