java - Strange behaviour of synchronized -


class testsync { public static void main(string[] args) throws interruptedexception {     counter counter1 = new counter();     counter counter2 = new counter();     counter counter3 = new counter();     counter counter4 = new counter();      counter1.start();     counter2.start();     counter3.start();     counter4.start();      counter1.join();     counter2.join();     counter3.join();     counter4.join();      (int = 1; <= 100; i++) {         if (values[i] > 1) {             system.out.println(string.format("%d visited %d times", i, values[i]));         } else if (values[i] == 0) {             system.out.println(string.format("%d wasn't visited", i));         }     } }  public static integer count = 0; public static int[] values = new int[105];  static {     (int = 0; < 105; i++) {         values[i] = 0;     } }  public static void incrementcount() {     count++; }  public static int getcount() {     return count; }  public static class counter extends thread {     @override     public void run() {         {             synchronized (count) {                 incrementcount();                  values[getcount()]++;             }         } while (getcount() < 100);     } } 

}

that code 1 online course. task make code visit each element of array once (only elements 1 100). have added simple synchronized block run method. in case of using values inside of statement works. count doesn't want work.

what difference? both of objects static fields inside of same class. have tried make count volatile hasn't helped me.

ps: lot of elements visited 2 times , of them 3 times. in case of using values in synchronized elements visited once!!!

integer immutable. moment call increment method, new object , reference of count variable gets changed , hence leads issue.


Comments

Popular posts from this blog

java - Plugin org.apache.maven.plugins:maven-install-plugin:2.4 or one of its dependencies could not be resolved -

Round ImageView Android -

How can I utilize Yahoo Weather API in android -