Last active
February 17, 2022 22:16
-
-
Save rubykv/3ac6a3012ea93bc8d7a3a795aea9201b to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.example.concurrent.config; | |
import java.util.concurrent.locks.Lock; | |
import java.util.concurrent.locks.ReadWriteLock; | |
import java.util.concurrent.locks.ReentrantLock; | |
import java.util.concurrent.locks.ReentrantReadWriteLock; | |
public class ExecutorServiceSample { | |
public static void main(String[] args) throws InterruptedException { | |
MySynchronizedBlock b = new MySynchronizedBlock(); | |
Thread t1 = new Thread(() -> { | |
System.out.println("Start 1st thread"); | |
Thread.currentThread().setName("Thread 1"); | |
b.testLock(); | |
}); | |
Thread t2 = new Thread(() -> { | |
System.out.println("Start 2nd thread"); | |
Thread.currentThread().setName("Thread 2"); | |
b.testLock(); | |
}); | |
t1.start(); | |
t2.start(); | |
} | |
} | |
class MySynchronizedBlock { | |
//Get Lock per Instance | |
ReadWriteLock wl = new ReentrantReadWriteLock(); | |
public void testLock() { | |
//Acquire Read Lock | |
wl.readLock().lock(); | |
try { | |
System.out.println("In read lock " + Thread.currentThread().getName()); | |
Thread.sleep(1000); | |
} catch (InterruptedException e) { | |
e.printStackTrace(); | |
} finally { | |
System.out.println("in read unlock " + Thread.currentThread().getName()); | |
wl.readLock().unlock(); | |
} | |
//Acquire Write Lock | |
wl.writeLock().lock(); | |
try { | |
System.out.println("In write lock " + Thread.currentThread().getName()); | |
Thread.sleep(1000); | |
} catch (InterruptedException e) { | |
e.printStackTrace(); | |
} finally { | |
System.out.println("In write unlock " + Thread.currentThread().getName()); | |
wl.writeLock().unlock(); | |
} | |
System.out.println("Method Ends... " + Thread.currentThread().getName()); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment