简体   繁体   中英

java thread pools and variable parameters

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.

In your example g is a primitive constant so you cannot change it. On the other side it has to be a constant in order to be accessed from the Runnable implementation. If you want to modify it you have to use some thread safe class like AtomicInteger.

Try this:

    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);
            }
        });
    }

In your example, you could move the declaration of g into the for loop, assign i to the final g , and use that in 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);
    }
  });
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM