Advertisement
Kostiggig

Reentrant Synchronised Block

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