Advertisement
Guest User

Untitled

a guest
Jul 15th, 2019
72
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 0.78 KB | None | 0 0
  1. public class RaceCondition {
  2.    
  3.    
  4.     public static void main(String[] args) throws InterruptedException {
  5.         Counter c = new Counter();
  6.         Runnable r = () -> {
  7.             for (int i = 0; i < 100_000; i++) {
  8.                 c.increment();
  9.             }
  10.         };
  11.  
  12.         Thread t1 = new Thread(r);
  13.         Thread t2 = new Thread(r);
  14.         Thread t3 = new Thread(r);
  15.  
  16.         t1.start();
  17.         t2.start();
  18.         t3.start();
  19.  
  20.         t1.join();
  21.         t2.join();
  22.         t3.join();
  23.  
  24.         System.out.println(c.getValue());
  25.     }
  26. }
  27.  
  28. class Counter {
  29.     private int value;
  30.  
  31.     public void increment() {
  32.         synchronized (this) {
  33.             value += 1;
  34.         }
  35.     }
  36.  
  37.     public int getValue() {
  38.         return value;
  39.     }
  40. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement