what is happening in the Synchronized block. ?
Guys please explain me using easy english words . because the above program which i posted is from a book. i can't easily understand what they are trying to say . i felt it is too hard for me to understand.
vignesh gopalakrishnan wrote:yes it is . its JAVA 2 complete reference 5th edition by herbert schildt , and the page number is (295,296,297) .. .please help me to get a clear understanding of the concept.
Basically, a synchronized block cannot be run by more than one Thread at once. The object specified in the synchronized(object) statement is used as a lock, which only one Thread at a time can acquire. When it has finished running the code inside the block, the lock is released so that another Thread can acquire it. So basically, when you have several Threads trying to run that block at the same time, they form a queue.
There's a bit more to know: For example, the next Thread in the queue is usually guaranteed to "see" the results of any update done by a previous one inside the same block. Also, a synchronized method for an object will use the same lock as a synchronized block for that object, so any Threads wanting to execute them will also have to wait until the lock is released.
If you need to know anything more (and there is a fair bit to know), you really should read the Java Tutorials. Anything you get here is only likely to scratch the surface.
Isn't it funny how there's always time and money enough to do it WRONG?
Joined: Oct 13, 2005
Sorry for the delay; it took some time to find my copy, which is the 8th edition, and the example is on pages 243ff. I think you ought to get a more recent copy than 5th edition. Anything which predates Java5 is probably seriously out of date.
Doesn’t the explanation in the book answer your question?