/** * A very simple program, just add to a single counter on * several threads all running at the same time. The point is * that the standard long will loose some counts along the way * because the threads will interact. * * This version differs from CCounter in that it uses the Executor * classes from the Java Concurrent libraries so it can limit the * number of running threads. * * @author gtowell * Created Nov 2022 */ import java.util.concurrent.Executors; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; public class EPCounter { // this is the shared memory !!! public long countt = 0; /** * a private class to implement the stuff that will ge run * in a separate thread. */ private class TCounter implements Runnable { long reps; public TCounter(long reps) { this.reps = reps; } public void run() { //System.err.println("Start " + this); for (long j = 0; j < reps; j++) countt++; } } /** * Test with unprotected long as shared memory * @param reps * @param threadsToStart */ public void testt(long reps, long threadsToStart) { ThreadPoolExecutor pool = (ThreadPoolExecutor)Executors.newFixedThreadPool(1000); for (long i = 0; i < threadsToStart; i++) { pool.execute(new TCounter(reps)); } pool.shutdown(); try { pool.awaitTermination(60, TimeUnit.SECONDS); } catch (Exception ee) { } /** * This is the fully done way to shut down the pool try { // Wait a while for existing tasks to terminate if (!pool.awaitTermination(60, TimeUnit.SECONDS)) { pool.shutdownNow(); // Cancel currently executing tasks // Wait a while for tasks to respond to being cancelled if (!pool.awaitTermination(60, TimeUnit.SECONDS)) System.err.println("Pool did not terminate"); } } catch (InterruptedException ie) { // (Re-)Cancel if current thread also interrupted pool.shutdownNow(); // Preserve interrupt status Thread.currentThread().interrupt(); } */ } public static void main(String[] args) { EPCounter cc = new EPCounter(); long r = 10000000; // word in each thread long t = 1000; // number of threads cc.testt( r, t); System.out.format("Long %d\n", cc.countt); System.out.format("Expected %d\n", r*t); } }