/** * 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. * * @author gtowell * Created Aug 2022 * Modified: Nov 2022 gtowell */ public class BCounter { // 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 extends Thread { private long reps; /** * Set up the class * @param reps the amount of work to do */ public TCounter(long reps) { this.reps = reps; } public void run() { 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) { // hold each thread object so it can be asked if it is running TCounter[] obs = new TCounter[(int) threadsToStart]; // start the threads for (int i = 0; i < threadsToStart; i++) { obs[i] = new TCounter(reps); obs[i].start(); } boolean live = true; // true is threads are running int chk = 0; // count the number of times you have checked // check if thread are running in a busy loop. while (live) { try { Thread.sleep(50); } catch (Exception e) { } live = false; for (TCounter tc : obs) { live = live || tc.isAlive(); } System.out.println(live + " " + chk++); } } public static void main(String[] args) { BCounter cc = new BCounter(); long r = 100000000; // word in each thread long t = 100; // number of threads cc.testt( r, t); System.out.format("Long %d\n", cc.countt); System.out.format("Expected %d\n", r*t); } }