Advertisement
Kostiggig

Custom lock incrementation

Apr 30th, 2023
661
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.71 KB | None | 0 0
  1. package multithreading.lock;
  2.  
  3. public class CustomLock {
  4.  
  5.     private boolean isLocked = false;
  6.  
  7.     public void lock() throws InterruptedException {
  8.         synchronized(this) {
  9.             while(isLocked) wait();
  10.             isLocked = true;
  11.         }
  12.     }
  13.  
  14.     public void unlock() {
  15.         synchronized(this) {
  16.             if(isLocked) {
  17.                 isLocked = false;
  18.                 notify();
  19.             }
  20.         }
  21.     }
  22. }
  23.  
  24. package multithreading.lock;
  25.  
  26. public class SomeObject {
  27.  
  28.     private final CustomLock lock = new CustomLock();
  29.  
  30.     public long count = 0;
  31.  
  32.     public void inc() throws InterruptedException {
  33.         lock.lock();
  34.         count++;
  35.         lock.unlock();
  36.     }
  37. }
  38.  
  39. package multithreading.lock;
  40.  
  41. import java.util.ArrayList;
  42. import java.util.List;
  43.  
  44. public class Client {
  45.  
  46.     public static void main(String[] args) {
  47.         SomeObject someObject = new SomeObject();
  48.  
  49.         List<Thread> threads = new ArrayList<>();
  50.  
  51.         for (int i = 0; i < 500_000; i++) {
  52.             threads.add(new Thread(() -> incTask(someObject), "Thread " + i));
  53.         }
  54.  
  55.         threads.forEach(Thread::start);
  56.  
  57.         // Join all threads to complete
  58.         threads.forEach(thread -> {
  59.             try {
  60.                 thread.join();
  61.             } catch (InterruptedException e) {
  62.                 throw new RuntimeException(e);
  63.             }
  64.         });
  65.  
  66.         System.out.println(
  67.                 "Value of count is " + someObject.count
  68.         );
  69.     }
  70.  
  71.     private static void incTask(SomeObject someObject) {
  72.         try {
  73.             someObject.inc();
  74.         } catch (InterruptedException e) {
  75.             throw new RuntimeException(e);
  76.         }
  77.     }
  78. }
  79.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement