• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Block synchronization

 
tom Su
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
  • 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
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic