How to add syncronization properly Java

后端 未结 4 1922
孤城傲影
孤城傲影 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条回答
  •  梦毁少年i
    2021-01-27 18:46

    Just use BlockingQueue as a container for elements that producer produces and consumer consumes:

    public class UsingSharedInt {
    
           private BlockingQueue q = new ArrayBlockingQueue<>(100);
    
           public void setSharedInt( int val )
           {
              System.err.println( Thread.currentThread().getName() +
              " setting sharedInt to " + val );
              q.add(val); // puts val into the queue
           }
    
           public int getSharedInt()
           {
             int val = q.take(); // waits for element to become available in queue, then returns one
             System.err.println( Thread.currentThread().getName() +
             " retrieving sharedInt value " + val);
             return val;
           }
       }
    

提交回复
热议问题