Sommaire

Concurrence TD 2

Data race, entrelacement et JIT

Exercice 0

When things add up

Récupérez la classe Counter.java et exécutez-la plusieurs fois.

public class Counter {
  private int value;

  public void addALot() {
    for (var i = 0; i < 100_000; i++) {
      this.value++;
    }
  }
  public static void main(String[] args) {
    var counter = new Counter();
    var thread1 = Thread.ofPlatform().start(counter::addALot);
    var thread2 = Thread.ofPlatform().start(counter::addALot);
    try {
      thread1.join();
      thread2.join();
    } catch (InterruptedException e) {
      throw new AssertionError();
    }
    IO.println(counter.value);
    }
  }
}

Essayez d'expliquer ce que vous observez.

Est-il possible que ce code affiche moins que 100 000 ? Expliquer précisément pourquoi.

esc

↑↓ parcourir ↵ ouvrir trouvé dans texte ou dans du code