*
The moose likes Threads and Synchronization and the fly likes Block synchronization Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Threads and Synchronization
Bookmark "Block synchronization" Watch "Block synchronization" New topic
Author

Block synchronization

tom Su
Greenhorn

Joined: May 05, 2001
Posts: 7
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
 
Don't get me started about those stupid light bulbs.
 
subject: Block synchronization
 
Similar Threads
Battleships - guys please help me out!
Thread problem
JAVA is a SHY animal, no need for synchronization
thread synchronization fail
Parallel running quicksort