Quantcast
Channel: silveira neto » Java
Viewing all articles
Browse latest Browse all 11

parallel counting in Java using AtomicInteger

$
0
0
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.TimeUnit;

class ParallelCounterExample {
   public static void main(String[] args) throws InterruptedException {
      int threads = 2000;
      ExecutorService executor = Executors.newFixedThreadPool(threads);
      final AtomicInteger atomi = new AtomicInteger();
      for(int i=0; i<threads; i++) {
         executor.execute( new Runnable() {
            @Override
            public void run() {
               atomi.getAndIncrement();
            }
         });
      }
      executor.awaitTermination(1, TimeUnit.SECONDS);
      executor.shutdown();
      System.out.println(atomi.get());
    }
}

Viewing all articles
Browse latest Browse all 11

Trending Articles