我做了這個簡單的線程減法程序。 它工作正常,但在輸出結束時,它會給出3個隨機值。我不知道如何防止這一點,任何想法? 我還必須計算每個線程減少了多少次計數器。有人可以幫助我嗎?Simple MultiThreads程序錯誤輸出
public class ThreadsExample implements Runnable {
static int counter = 100000;
static long time;
static long endtime;
static float finaltime;
static int value;
static void incrementCounter() {
System.out.println(Thread.currentThread().getName() + ": " + counter);
counter--;
}
@Override
public void run() {
time = System.nanoTime();
while (counter >= 0) {
incrementCounter();
}
endtime = System.nanoTime() - time;
finaltime = endtime;
System.out.println(finaltime/1000000000 + " sekundy");
}
public static void main(String[] args) throws InterruptedException {
ThreadsExample threads = new ThreadsExample();
Thread thread1 = new Thread(threads);
Thread thread2 = new Thread(threads);
Thread thread3 = new Thread(threads);
Thread thread4 = new Thread(threads);
thread1.start();
thread2.start();
thread3.start();
thread4.start();
if (counter <= 0) {
System.out.println("Thread 1,2,3,4^^^");
}
}
}
首先,您將ThreadExample的同一個實例傳遞給每個線程。這可能會導致一些內部狀態異常。嘗試爲每個線程構造函數創建一個新的ThreadsExample。它看起來像每個ThreadsExample將基本上同時停止,因爲「counter」是靜態的,並且所有實例都會在基本相同的確切時間檢測到「counter <0」。這是預期的嗎?或者你想讓每個線程管理自己的獨立計數器? – pacifier21
你沒有任何形式的同步。因此,每個線程可能會讀取一些值'> 0'並減少'counter',這樣'counter'就會以某個值<<0結束。此外,每個線程都會將'finaltime'設置爲一個值,您在那裏有一個競爭條件。 – Turing85