Facebook
From triitri, 6 Years ago, written in Plain Text.
Embed
Download Paste or View Raw
Hits: 339
  1. class Counter {
  2.     private int value;
  3.  
  4.     public void increment() {
  5.         value += 1;
  6.     }
  7.  
  8.     public int getValue() {
  9.         return value;
  10.     }
  11. }
  12.  
  13. public class RaceCondition {
  14.     public static void main(String[] args) throws InterruptedException {
  15.         Counter c = new Counter();
  16.         Runnable r = () -> {
  17.             for (int i = 0; i < 100_000; i++) {
  18.                 c.increment();
  19.             }
  20.         };
  21.  
  22.         Thread t1 = new Thread(r);
  23.         Thread t2 = new Thread(r);
  24.         Thread t3 = new Thread(r);
  25.  
  26.         t1.start();
  27.         t2.start();
  28.         t3.start();
  29.  
  30.         t1.join();
  31.         t2.join();
  32.         t3.join();
  33.  
  34.         System.out.println(c.getValue());
  35.     }
  36. }