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

Sandra Bachan
Ranch Hand
Posts: 434
Chapter 9, Sierra/Bates, Multithreading, Wait(), Notify() section:

Output:

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

How does this happen?

Greenhorn
Posts: 22

this is adding number from 0 to 99 into total.

total = 0+1+2+3+4+5+..........................99

Mike Peters
Ranch Hand
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

Bert Bates
author
Sheriff
Posts: 8898
5
Hi Guys,

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

hth,

Bert

Kevin Kilbane
Ranch Hand
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
Posts: 434
1 + 2 + 3 + ... + n = n * (n + 1) / 2

Wow, I totally forgot about that.