我不明白爲什麼計數器的輸出每次都是不同的隨機數。當我在run()方法中打印出計數器時,它每次都是100000,但是當我評論該語句時,它會給出一個隨機數。在run()方法中,爲什麼counter是一個隨機數?
public class Answer extends Thread {
private static int counter = 0;
private static final int THREADS = 4;
public static final int COUNT = 100000;
public static void main(String[] args) {
Answer[] threads = new Answer[THREADS];
for (int i = 0; i < THREADS; i++) {
threads[i] = new Answer();
threads[i].start();
}
try {
for (int i = 0; i < THREADS; i++) {
threads[i].join();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Counter: " + counter);
}
public void run() {
for (int i = 0; i < COUNT/THREADS; i++) {
counter++;
//System.out.println(counter);
}
} }
爲什麼你認爲讓「反」成爲靜態會是一個好主意?你是否經常宣佈變量是靜態的?你爲什麼要那麼做? –