aspose file tools*
The moose likes Threads and Synchronization and the fly likes Thread coordination. Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Soft Skills this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Java » Threads and Synchronization
Bookmark "Thread coordination." Watch "Thread coordination." New topic
Author

Thread coordination.

sam White
Ranch Hand

Joined: Feb 18, 2011
Posts: 208
Hi,

In the following program, I want the program prints exactly 2000 when the main program exit.



But it prints > 1000 in different result each time.
Is there any better way to make the println to print 2000?

Thanks
S
Sudheer Bhat
Ranch Hand

Joined: Feb 22, 2011
Posts: 75
I changed your run to below.


Now you will get 2000 always. No need to have the setCount and getCount as synchronized operations anymore.
sam White
Ranch Hand

Joined: Feb 18, 2011
Posts: 208
Hi, thank you very much for the code.
Would the following explanation adequate?

a) Without synchronized, when the main method exits the value of count.getCount would be any value greater than 1000, since the method is not thread-safe.

b) After introduced the third runner C, and make the following method thread-safe, this makes each thread have to wait for another thread finish running on the method before
starting increase the value of count from its previous value. Therefore when all threads are completed their execution, the final result of setCount would be 3000.
public void run() {
synchronized(count) {
for (int i = 1; i <= 1000; i++) {
count.setCount(count.getCount() + 1);
}
}
}


Can anyone give comment about my answers?
Thanks
SS
harish sr
Greenhorn

Joined: Sep 02, 2011
Posts: 3
why is the join required here?
sam White
Ranch Hand

Joined: Feb 18, 2011
Posts: 208
Join allows one thread wait for another thread to finish before the current thread exit.
The current thread in this case is Main.
But I think the main problem is the original program is not thread-safe. But some people said I didn't explained the cause of the problem by just saying "not thread-safe".
Any opinion?
John Vorwald
Ranch Hand

Joined: Sep 26, 2010
Posts: 139
I assume this is a homework assignment, but it's not clear what the teacher wants you to learn.
Sudheer's solution is to modify the data object assessor, to first check if the data is less than 2000 before adding.
A different modification is to change the data assessor to only store if the data is less than 2000.




But, it is interesting what happens if you comment out the runnerC variable, so only two variables run. I would expect / hope that you would get with the modification below, but you don't get 2000, or a repeatable number.



produces




Here is the code testing a number of evaluations.

 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Thread coordination.