Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package multithreading.lock.reentrant_custom_lock_success;
- public class CustomReentrantLock {
- private boolean isLocked = false;
- private Thread lockedBy = null;
- private int lockedCount = 0;
- public void lock() throws InterruptedException {
- synchronized(this) {
- while(isLocked && Thread.currentThread() != lockedBy) wait();
- lockedBy = Thread.currentThread();
- lockedCount++;
- isLocked = true;
- }
- }
- public void unlock() {
- synchronized(this) {
- if(Thread.currentThread() == lockedBy) {
- lockedCount--;
- if(lockedCount == 0) {
- lockedBy = null;
- isLocked = false;
- notify();
- }
- }
- }
- }
- }
- package multithreading.lock.reentrant_custom_lock_success;
- import multithreading.lock.custom_lock.CustomLock;
- public class ReentrantCustomLockSuccessExample {
- private final CustomReentrantLock lock = new CustomReentrantLock();
- public synchronized void outer() throws InterruptedException {
- lock.lock();
- System.out.println(Thread.currentThread().getName() + " enters OUTER");
- Thread.sleep(500);
- inner();
- lock.unlock();
- }
- private synchronized void inner() throws InterruptedException {
- lock.lock();
- System.out.println(Thread.currentThread().getName() + " tries to enter INNER");
- System.out.println(Thread.currentThread().getName() + " enters INNER");
- lock.unlock();
- }
- }
- package multithreading.lock.reentrant_custom_lock_success;
- public class ReentrantCustomLockSuccessExampleClient {
- public static void main(String[] args) throws InterruptedException {
- ReentrantCustomLockSuccessExample reentrantCustomLockFailExample = new ReentrantCustomLockSuccessExample();
- for (int i = 0; i < 5; i++) {
- new Thread(() -> {
- try {
- reentrantCustomLockFailExample.outer();
- } catch (InterruptedException e) {
- throw new RuntimeException(e);
- }
- }, "Thread " + i).start();
- }
- Thread.sleep(7000); // needed to wait all threads to be completed (I'm lazy to call join on them after starting =) )
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement