This week's book giveaway is in the OO, Patterns, UML and Refactoring forum. We're giving away four copies of Refactoring for Software Design Smells: Managing Technical Debt and have Girish Suryanarayana, Ganesh Samarthyam & Tushar Sharma on-line! See this thread for details.
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."
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
Joined: Oct 21, 2007
Dear marc weber What happen when run() method like this-
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?
Joined: Oct 21, 2007
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.