Zastanawiam o wyniku niebezpiecznej zmniejszanie/zwiększając w wątkach Javie, więc jest mój program:Wątek niebezpieczny dekompresowanie/inkrementowanie - dlaczego w większości pozytywne?
główne klasy:
public class Start {
public static void main(String[] args) {
int count = 10000000, pos = 0, neg = 0, zero = 0;
for (int x=0; x<10000; x++) {
Magic.counter = 0;
Thread dec = new Thread(new Magic(false, count));
Thread inc = new Thread(new Magic(true, count));
dec.start();
inc.start();
try {
inc.join();
dec.join();
} catch (InterruptedException e) {
System.out.println("Error");
}
if (Magic.counter == 0)
zero++;
else if (Magic.counter > 0)
pos++;
else
neg++;
}
System.out.println(Integer.toString(neg) + "\t\t\t" + Integer.toString(pos) + "\t\t\t" + Integer.toString(zero));
}
}
wątki klasa:
public class Magic implements Runnable {
public static int counter = 0;
private boolean inc;
private int countTo;
public Magic(boolean inc, int countTo) {
this.inc = inc;
this.countTo = countTo;
}
@Override
public void run() {
for (int i=0;i<this.countTo;i++) {
if (this.inc)
Magic.counter++;
else
Magic.counter--;
}
}
}
Mam biegać program kilka razy i zawsze uzyskując znacznie bardziej pozytywny wynik, a następnie ujemny. Próbowałem również zmienić kolejność wątków, ale nic to nie zmieniło. Niektóre wyniki:
Number of results < 0 | Number of results > 0 | Number of results = 0
1103 8893 4
3159 6838 3
2639 7359 2
3240 6755 5
3264 6728 8
2883 7112 5
2973 7021 6
3123 6873 4
2882 7113 5
3098 6896 6
Możesz chcieć uczynić Magic.counter zmienna lotny, poza operacje mogą zostać zmieniona i/lub jego wartość może być buforowane per-thread w rejestrze. – prunge