• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Thread coordination.

 
sam White
Ranch Hand
Posts: 229
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 75
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 229
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
why is the join required here?
 
sam White
Ranch Hand
Posts: 229
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 139
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.

 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic