Advertisement
Kostiggig

ReentrantCustomLockFailExample

Apr 30th, 2023
742
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.54 KB | None | 0 0
  1. package multithreading.lock.reentrant_custom_lock_fail;
  2.  
  3. import multithreading.lock.custom_lock.CustomLock;
  4. import org.checkerframework.checker.units.qual.C;
  5.  
  6. public class ReentrantCustomLockFailExample {
  7.  
  8.     private final CustomLock lock = new CustomLock();
  9.     public synchronized void outer() throws InterruptedException {
  10.         lock.lock();
  11.         System.out.println(Thread.currentThread().getName() + " enters OUTER");
  12.         Thread.sleep(500);
  13.         inner();
  14.         lock.unlock();
  15.     }
  16.  
  17.     private synchronized void inner() throws InterruptedException {
  18.         lock.lock();
  19.         System.out.println(Thread.currentThread().getName() + " tries to enter INNER");
  20.         System.out.println(Thread.currentThread().getName() + " enters INNER");
  21.         lock.unlock();
  22.     }
  23. }
  24.  
  25. package multithreading.lock.reentrant_custom_lock_fail;
  26.  
  27. public class ReentrantCustomLockFailExampleClient {
  28.  
  29.     public static void main(String[] args) throws InterruptedException {
  30.         ReentrantCustomLockFailExample reentrantCustomLockFailExample = new ReentrantCustomLockFailExample();
  31.         for (int i = 0; i < 5; i++) {
  32.             new Thread(() -> {
  33.                 try {
  34.                     reentrantCustomLockFailExample.outer();
  35.                 } catch (InterruptedException e) {
  36.                     throw new RuntimeException(e);
  37.                 }
  38.             }, "Thread " + i).start();
  39.         }
  40.  
  41.         Thread.sleep(7000); // needed to wait all threads to be completed (I'm lazy to call join on them after starting =) )
  42.     }
  43. }
  44.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement