As the integers are produced the Consumer thread sums their value (1+2+3…+10=55)
Producer thread generates integers from 1 to 10
The program is meant to produce
The reason why this does not work, and could not possibly work, is that your shared int
is only capable of containing a single value. So, even if you made your getter and setter synchronized, (public synchronized void
instead of public void
, or using a private lock
object) one thread could still write two values before the other thread gets the chance to read any, and one thread could read the same value twice before the other thread gets a chance to replace it with a new value.
So, you have two options:
Make UsingSharedInt
contain an Integer
instead of an int
, and:
Make the setter loop until the value is null before replacing it with a non-null value. This way, a value will never be overwritten.
Make the getter loop until the value is non-null before fetching it, and then set it to null before returning the value. This way, a value will never be read twice.
As Sasha Salauyou suggested, use a BlockingQueue
; one thread adds integers to the queue, while the other thread removes integers from the queue and processes them. This is the best approach.