@Override // Keep subtracting an amount from the account public void run() { while (true) { account.withdraw((int) (Math.random() * 10) + 1); } }
@Override // Keep adding an amount to the account public void run() { try { // Purposely delay it to let the withdraw method proceed while (true) { account.deposit((int) (Math.random() * 10) + 1); Thread.sleep(1000); } } catch (InterruptedException ex) { ex.printStackTrace(); } }
public static void main(String[] args) { ExecutorService executor = Executors.newCachedThreadPool(); // Create and launch 100 threads for (int i = 0; i < 100; i++) { executor.execute(new AddPennyTask()); } executor.shutdown(); // Wait until all tasks are finished while (!executor.isTerminated()) {} System.out.println("What is balance? " + account.getCount()); }
public void run() { account.deposit(1); }