我想了解一下不安全遞減的結果/ Java中的線程遞增,所以我的程序:線程不安全遞減/遞增 - 爲什麼主要是正面的?
主要類:
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));
}
}
主題類:
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--;
}
}
}
我已經運行編程幾次,並總是獲得更積極的結果,然後消極。我也嘗試改變哪些線程開始的順序,但這並沒有改變。一些結果:
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
你可能想使Magic.counter變量波動,否則操作可以重新排序和/或它的價值可能每個線程的寄存器進行緩存。 – prunge