wood burning stoves 2.0*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Multithreading: How can total be nearly 5,000 even though loop is up to 100? 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 "Multithreading: How can total be nearly 5,000 even though loop is up to 100?" Watch "Multithreading: How can total be nearly 5,000 even though loop is up to 100?" New topic
Author

Multithreading: How can total be nearly 5,000 even though loop is up to 100?

Sandra Bachan
Ranch Hand

Joined: Feb 18, 2010
Posts: 434
Chapter 9, Sierra/Bates, Multithreading, Wait(), Notify() section:



Output:

Waiting for b to complete...
Total is: 4950


How does this happen?


Marriage Made in Heaven
http://www.youtube.com/user/RohitWaliaWedsSonia
Pradeep Kr
Greenhorn

Joined: Feb 17, 2010
Posts: 22

this is adding number from 0 to 99 into total.

total = 0+1+2+3+4+5+..........................99
Mike Peters
Ranch Hand

Joined: Oct 10, 2009
Posts: 67

1 + 2 + 3 + ... + n = n * (n + 1) / 2

you better start thread b from within the synchronization block.

edit:
I think the proof is something like this:
0 + ... + n = n * (n + 1) / 2

n = 0: 0 = 0 * 2 / 2 = 0

suppose 0 + ... + n = n * (n + 1) / 2 is true

prove: 0 + ... + n + 1 = (n + 1) * (n + 2) / 2

0 + ... + n + 1
= {trivial}
0 + ... + + n + n + 1
= {1 + ... + n = n * (n + 1) / 2}
n * (n + 1) / 2 + n + 1
= {x = y * x / y}
n * (n + 1) / 2 + 2 * (n + 1) / 2
= {x / z + y / z = (x + y) / z}
(n * (n + 1) + 2 * (n + 1)) / 2
= {x * z + y * z = (x + y) * z}
((n + 1) * (n + 2)) / 2
= {trivial}
(n + 1) * (n + 2) / 2


Mike Peters
Bert Bates
author
Sheriff

Joined: Oct 14, 2002
Posts: 8764
    
    5
Hi Guys,

The wait() and notify() topics are good topics, but they've been removed from the SCJP exam.

hth,

Bert


Spot false dilemmas now, ask me how!
(If you're not on the edge, you're taking up too much room.)
Kevin Kilbane
Ranch Hand

Joined: Sep 22, 2008
Posts: 42
Bert Bates wrote:Hi Guys,

The wait() and notify() topics are good topics, but they've been removed from the SCJP exam.

hth,

Bert

They are not in SCJP6 but are still in SCJP5 - correct?
Sandra Bachan
Ranch Hand

Joined: Feb 18, 2010
Posts: 434
1 + 2 + 3 + ... + n = n * (n + 1) / 2



Wow, I totally forgot about that.

 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Multithreading: How can total be nearly 5,000 even though loop is up to 100?
 
Similar Threads
Lock Mechanism ?
wait(),notify() problem
wait and notify help needed
wait and notify problem from K&B.
notify(); doesn't work?