2015-05-11 26 views
4

我有一個是這樣的:並行使用Java 7的結果,使用非最終變量

int [] array1 = new int[20]; 
int [] array2 = new int[20]; 
int total= 0; 
Random generator = new Random(); 

for(int i = 0; i < 10000; i++){ 
    int tmp = generator.nextInt(20); 
    boolean win = custom_function(...); 
    array1[tmp]++; 
    array2[tmp]++ 
    total++; 
} 

// do something with the arrays 

而且我不知道如何實現它並行!當使用結構,如

ExecutorService exec = 
    Executors.newFixedThreadPool(SOME_NUM_OF_THREADS); 
try { 
    for (final Object o : list) { 
     exec.submit(new Runnable() { 
      @Override 
      public void run() { 
       // do stuff with o. 
      } 
     }); 
    } 
} finally { 
    exec.shutdown(); 
} 

我簡單的不能什麼或改變什麼,因爲它只有最後變量的作品!如何進行?


每個可運行應該修改變量array1[tmp]array2[tmp]array3[tmp]。請注意,這可以通過某種分叉連接完成,我只是不知道該怎麼做。

+2

你怎麼想它並行? (如果每個Runnable能夠返回結果,應該做些什麼?) – Radiodef

+0

每個可運行的應該修改變量array1 [tmp],array2 [tmp]和array3 [tmp]。請注意,這可以通過某種分叉連接來完成,我只是不知道該怎麼做... –

回答

1

看起來好像你實際上想要Callable,計算結果,而不是Runnable

submit(Callable)返回Future,您可以撥打get並檢索結果。

import java.util.*; 
import java.util.concurrent.*; 

class Example { 
    public static void main(String[] args) { 
     final int n = 3; 
     final int length = 20; 

     ExecutorService ex = Executors.newFixedThreadPool(n); 
     List<Future<int[]>> futures = new ArrayList<>(); 

     for (int i = 0; i < n; ++i) { 
      futures.add(ex.submit(new Callable<int[]>() { 
       Random r = new Random(); 

       @Override 
       public int[] call() { 
        int[] result = new int[length]; 

        for (int i = 0; i < length; ++i) { 
         int tmp = r.nextInt(length); 
         result[tmp]++; 
        } 

        return result; 
       } 
      })); 
     } 

     ex.shutdown(); 

     for (Future<int[]> f : futures) { 
      try { 
       System.out.println(Arrays.toString(f.get())); 
      } catch (InterruptedException|ExecutionException e) { 
       e.printStackTrace(); 
      } 
     } 
    } 
} 

輸出示例:

[0, 1, 1, 1, 0, 1, 0, 2, 3, 1, 2, 0, 1, 2, 0, 2, 1, 2, 0, 0] 
[2, 2, 1, 0, 0, 2, 1, 1, 3, 1, 2, 1, 0, 0, 1, 1, 0, 1, 1, 0] 
[0, 1, 1, 1, 0, 1, 0, 4, 1, 2, 0, 1, 0, 1, 2, 2, 1, 0, 0, 2] 
+0

這應該是謝謝(: –

+0

記得查看我鏈接到的文檔以及;)這些方法拋出你應該瞭解的各種例外。 – Radiodef