How to add syncronization properly Java

后端 未结 4 1915
孤城傲影
孤城傲影 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:51

    The problem is not only concurrent access to the shared int. There is some queueing logic to look at.

    In the code, the Producer loops and set the value of SharedInt without waiting for it to be consumed by the Consumer. When the Consumer read a value, it will read some values between [1,10] and certainly the last one (10) since it is the exit condition in the while loop. But since each thread write/read the value at random times, you will not have the perfect sequence of write/read/write/read/etc. but something like write/write/read/write/write/read/read/etc...

    In order for this to work, you need to have the writing in the SharedInt to block after setting one value (or you need to queue the different values), until this value is read (consumed) by the Consumer thread. The same for reading by the Consumer, that must wait until a value is set by the producer.

    The easiest way to achieve that is to use a concurrent collection like BlockingQueue to store the shared integer. See the example of ProducerConsumer in the doc.

    You can implement this queue mechanism by yourself to experiment with low level sync, but it is not just a matter of putting a synchronized keyword around the SharedInt...

提交回复
热议问题