aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Thread synchronization problem Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Thread synchronization problem" Watch "Thread synchronization problem" New topic
Author

Thread synchronization problem

Prasun Howlader
Ranch Hand

Joined: Oct 21, 2007
Posts: 89


My problem is Line1.I do not understant acutally two threads execute this fun() method at the same time!When i remove synchronized keyword from run() method although the fun method is synchronized the program does not produce desire result.Please help me to solve this problem.


"Control time instead of letting time control you."
marc weber
Sheriff

Joined: Aug 31, 2004
Posts: 11343

Originally posted by Prasun Howlader:
...although the fun method is synchronized the program does not produce desire result...

The first thread that enters the synchronized run() method will keep the RunnableThread object's lock until it finishes looping and leaves the method.

But synchronizing the fun() method doesn't have an effect, because the fun() method just prints a single line. So each time fun() is called, the Thread1 object's lock is acquired, a line is printed, and then the lock is immediately released again.


"We're kind of on the level of crossword puzzle writers... And no one ever goes to them and gives them an award." ~Joe Strummer
sscce.org
Prasun Howlader
Ranch Hand

Joined: Oct 21, 2007
Posts: 89
Dear marc weber What happen when run() method like this-



and fun() method is-

marc weber
Sheriff

Joined: Aug 31, 2004
Posts: 11343

Synchronizing run() is the key. If run() is synchronized, then the first thread that enters the method will keep the lock until it finishes looping through all 5 iterations. But if run() is not synchronized, then the thread scheduler can alternate between the threads while they iterate through their loops. (The brief call to sleep just makes it more likely that the thread scheduler will switch between the two.)

I don't think that adding a sleep call to fun() will do anything other than slow it down. The fun() method is called with each iteration in the run() loop. And each time fun() executes, the lock is acquired and then released. (Remember, this is a different lock than what's being used in the run() method.)

What behavior (output) are you trying to get?
Prasun Howlader
Ranch Hand

Joined: Oct 21, 2007
Posts: 89
Thanks marc for your good explanation. Actually i want to see the result that the thread1 completes its execution then thread2 completes its job but do not use synchronized word in run method but using synchronized in the fun method.I think my problem is understanding synchronization.
 
Don't get me started about those stupid light bulbs.
 
subject: Thread synchronization problem