• 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

Block synchronization

 
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I come across this funny code, to stop it ocer-run, I have to do synchronized on the run() method. My Qs are.. 1) what's exact cause of over-run 50? 2)how to use block syn (synchrinzed(this) to stop this over-run?
package synchron;
public class synBlock {
public static void main(String args[]) {
Xyz r = new Xyz();
(new Thread(r)).start();
(new Thread(r)).start();
(new Thread(new Xyz())).start();
(new Thread(new Xyz())).start();
(new Thread(r)).start();
(new Thread(r)).start();
(new Thread(new Xyz())).start();
(new Thread(new Xyz())).start();
System.out.println("after all threads start ");
}// main
}
class Xyz implements Runnable {
int i = 5;
public void run() {
i = 35;
while (true) {
for(long j=0;j< (long)(Math.random()*1.e8); j++) { double dd =Math.log(2.5);}<br /> // synchronized on the block fails<br /> // synchronized on the statement System.out.print fails too<br /> synchronized (this) {<br /> System.out.print("i = " + i++ + " " ); }<br /> if ( i == 50 ) {<br /> System.out.println(" stop at lower bound i = " + i);<br /> break;<br /> }<br /> if ( i > 100 ) {
System.out.println(" stop at higher bound i = " + i);
break;
}
}// while
}
}// run
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
reply
    Bookmark Topic Watch Topic
  • New Topic