Commit cf28e00c authored by Trisha Gee's avatar Trisha Gee
Browse files

[Ch15] Modernising the missing update code, it's out of order but I still...

[Ch15] Modernising the missing update code, it's out of order but I still don't see any missing updates.
parent 1931db23
Loading
Loading
Loading
Loading
+16 −14
Changes for src/main/java/ch15/TestSyncTest.java: 16 added lines, 14 removed lines.
Original line number Diff line number Diff line
package ch15;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class TestSyncTest {
  public static void main(String[] args) {
    TestSync job = new TestSync();
    Thread a = new Thread(job);
    Thread b = new Thread(job);
    a.start();
    b.start();
  }
    ExecutorService pool = Executors.newFixedThreadPool(2);
    Balance balance = new Balance();
    pool.execute(() -> incrementBalance50Times(balance));
    pool.execute(() -> incrementBalance50Times(balance));
    pool.shutdown();
  }

class TestSync implements Runnable {
  private int balance;

  public void run() {
  private static void incrementBalance50Times(Balance balance) {
    for (int i = 0; i < 50; i++) {
      increment();
      System.out.printf("Balance updated by %s. Balance is %d%n", Thread.currentThread().getName(), balance);
      balance.increment();
      System.out.printf("Balance updated by %s. Balance is %d%n", Thread.currentThread().getName(), balance.balance);
    }
  }
}

class Balance {
  int balance;

  public void increment() {
    int i = balance;
    balance = i + 1;
    balance++;
  }
}