2015-04-26 66 views
5

我正嘗試在java中使用for循環創建多個線程,以便它們共享相同的變量計數器。我做錯了什麼,因爲我想讓計數器爲每個線程增加。如何在java中使用循環創建多個線程

這是輸出爲以下代碼:

計數器:1
計數器:1
計數器:1

public static void main(String[] args) { 
    int numThreads = 3; 
    for (int i = 0; i < numThreads; i++) { 
     Create c = new Create(); 
     Thread thread = new Thread(c); 
     thread.start(); 
    } 
} 


public class Create implements Runnable { 
    int counter = 0; 

    public void run() { 
     counter++; 
     System.out.println("Counter: " + counter); 
    } 
} 

回答

9

聲明counterstaticvolatile

static volatile int counter = 0; 

和所有3個線程將分享它。

注意,儘管波動性關注可見性(當一個線程更新它時 - 該更改將被其他線程看到),但它沒有考慮修改的原子性,因爲您應該同步該部分你增加它,或者更好的是,使用AtomicInteger

2

我的建議,(&拿起alfasin的編輯),請考慮此創建類的實現:

import java.util.concurrent.atomic.AtomicInteger; 

public class Create implements Runnable { 
    static AtomicInteger classCounter = new AtomicInteger(); 
    AtomicInteger objCounter = new AtomicInteger(); 
    public void run() { 
     System.out.println("Class Counter: " + classCounter.incrementAndGet()); 
     System.out.println("Object Counter: " + objCounter.incrementAndGet()); 
    } 
} 
+0

這'counter'會計算每一個線程類#run()'方法? – Tom

+0

不,目前它計算一個'Create'對象的運行方法(執行),爲了在課堂上達到這個目的,你需要使'counter'變成靜態的。 (或者在你的主要方法中:爲所有線程創建一個'Create') – xerx593

+2

好你知道嗎,那麼如何編輯你的代碼來匹配OP的要求呢? – Tom