/** * Atomicity and Java. The idea here is that atomicity is violated * when things on one thread interfere with processing on another thread. * In this small banking example, it is possible that a thread making * a withdrawal happens at the same time as one making a deposit. * In this program, if there is not violation, then the final * balance should be exactly the starting balance. * * See the java keyword synchronized for avoiding this violation. * * @author gtowell * Created Nov 2022 */ public class AC { // the opening balance int balance = 10000; // add to the balance public void deposit(int amt) { balance += amt; } // reduce the balance public void withdrawl(int amt) { balance += amt; } // A thread that does a lot of adding or subtracting private class DW extends Thread { int siz; int cnt; public DW(int cnt, int siz) { this.siz = siz; this.cnt = cnt; } public void run() { for (int i = 0; i < cnt; i++) { if (siz > 0) deposit(siz); else withdrawl(siz); } } } // do a lot of add or remove in separate threads. public void doo() { DW dep = new DW(100000, 50); DW wd = new DW(100000, -50); dep.start(); wd.start(); while (dep.isAlive() || wd.isAlive()) { try { Thread.sleep(50); } catch (Exception e) { } } System.out.println(balance); } public static void main(String[] args) { (new AC()).doo(); } }