How to add syncronization properly Java

后端 未结 4 1907
孤城傲影
孤城傲影 2021-01-27 17:56

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

4条回答
  •  囚心锁ツ
    2021-01-27 18:42

    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.

提交回复
热议问题