Advertisement
Guest User

Untitled

a guest
Dec 15th, 2019
106
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.00 KB | None | 0 0
  1. import java.util.concurrent.ExecutorService;
  2. import java.util.concurrent.Executors;
  3. import java.util.concurrent.TimeUnit;
  4.  
  5. import java.util.concurrent.atomic.AtomicInteger;
  6.  
  7. class AtomicCounter {
  8.     private AtomicInteger count = new AtomicInteger(0);
  9.  
  10.     public int incrementAndGet() {
  11.         return count.incrementAndGet();
  12.     }
  13.  
  14.     public int getCount() {
  15.         return count.get();
  16.     }
  17. }
  18.  
  19. public class AtomicIntegerExample {
  20.     public static void main(String[] args) throws InterruptedException {
  21.         ExecutorService executorService = Executors.newFixedThreadPool(2);
  22.  
  23.         AtomicCounter atomicCounter = new AtomicCounter();
  24.  
  25.         for(int i = 0; i < 1000; i++) {
  26.             executorService.submit(() -> atomicCounter.incrementAndGet());
  27.         }
  28.  
  29.         executorService.shutdown();
  30.         executorService.awaitTermination(60, TimeUnit.SECONDS);
  31.  
  32.         System.out.println("Final Count is : " + atomicCounter.getCount());
  33.     }
  34. }
  35.  
  36. // Output
  37. // Final Count is : 1000
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement