How to add syncronization properly Java

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

    Just add a temp int in Consumer to see if it's different from the last one.

    int val, sum, tmp = 0;
    do {
    // sleep for a random interval
      try { 
         Thread.sleep( (int) ( Math.random() * 3000 ) ); 
      }catch( InterruptedException e ) {
         System.err.println( e.toString() );
      }
      val = cHold.getSharedInt();
      if(val!=tmp){
        sum += val;
      }
      tmp = val;
    } while ( val != 10 );
    

提交回复
热议问题