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()); } }
↧
parallel counting in Java using AtomicInteger
↧