File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
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
JavaRanch » Java Forums » Java » Threads and Synchronization
Bookmark "Thread coordination." Watch "Thread coordination." New topic

Thread coordination.

sam White
Ranch Hand

Joined: Feb 18, 2011
Posts: 229

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?

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: 229
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?
harish sr

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

Joined: Feb 18, 2011
Posts: 229
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.


Here is the code testing a number of evaluations.

I agree. Here's the link:
subject: Thread coordination.
It's not a secret anymore!