0

Here is my code :

final int g = 0;

ExecutorService threadPool = Executors.newFixedThreadPool(10);
for (int i = 0; i < 10; i++) {
    threadPool.submit(new Runnable() {
        public void run() {
            g++;
            myFunc(g);
        }
    });
}

Obviously this doesn't work because of concurrent access on the variable g.

I've tried a lot of things, but didn't manage to find a nice and easy way to fix it. Any solutions ?

Thanks.

4

2 に答える 2

7

この例では、gはプリミティブ定数であるため、変更することはできません。一方、Runnable実装からアクセスするには、定数である必要があります。それを変更したい場合は、AtomicIntegerのようなスレッドセーフクラスを使用する必要があります。

これを試して:

    final AtomicInteger g = new AtomicInteger()

    ExecutorService threadPool = Executors.newFixedThreadPool(10);
    for (int i = 0; i < 10; i++) {
        threadPool.submit(new Runnable() {
            public void run() {
                int local = g.incrementAndGet();
                myFunc(local);
            }
        });
    }
于 2013-01-25T20:28:29.357 に答える
2

あなたの例では、の宣言をループに移動しgforに割り当てifinal g、それをで使用することができrun()ます。

ExecutorService threadPool = Executors.newFixedThreadPool(10);
for (int i = 0; i < 10; i++) {
  final int g = i+1;
  threadPool.submit(new Runnable() {
    public void run() {
      myFunc(g);
    }
  });
}
于 2013-01-25T20:57:28.453 に答える