fork download
  1. /* package whatever; // don't place package name! */
  2.  
  3. import java.util.concurrent.*;
  4. import java.util.concurrent.locks.ReentrantLock;
  5.  
  6. /* Name of the class has to be "Main" only if the class is public. */
  7. class Ideone
  8. {
  9. static class DemoClass {
  10. public int count =0;
  11. public ReentrantLock lock = new ReentrantLock();
  12. public void increment() {
  13. lock.lock();
  14. try {
  15. count++;
  16. } finally {
  17. lock.unlock();
  18. }
  19. }
  20. }
  21.  
  22. public static void main(String[] args) throws InterruptedException {
  23. ExecutorService executor = Executors.newFixedThreadPool(2);
  24. DemoClass demoClass = new DemoClass();
  25. int i=0;
  26. for(;i<=10000;i++) {
  27. executor.submit(demoClass::increment);
  28. }
  29.  
  30. executor.shutdown();
  31. executor.awaitTermination(2, TimeUnit.SECONDS);
  32.  
  33. demoClass.lock.lock();
  34. try {
  35. System.out.println( demoClass.count); // 10000
  36. } finally {
  37. demoClass.lock.unlock();
  38. }
  39. }
  40. }
Success #stdin #stdout 0.15s 56920KB
stdin
Standard input is empty
stdout
10001