Created
June 28, 2019 18:37
-
-
Save akshanshjain95/c8605eb5fd2019ebbf3796dc27a31ad8 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
import java.util.concurrent.locks.ReentrantLock; | |
public class ReentrantLockInterruptiblyDemo { | |
private static ReentrantLock reentrantLock = new ReentrantLock(); | |
public static void main(String[] args) throws InterruptedException { | |
ReentrantLockInterruptiblyDemo reentrantLockDemo = new ReentrantLockInterruptiblyDemo(); | |
Thread t1 = new Thread(new Runnable() { | |
@Override | |
public void run() { | |
reentrantLock.lock(); | |
reentrantLockDemo.checkSync(); | |
reentrantLock.unlock(); | |
} | |
}); | |
Thread t2 = new Thread(new Runnable() { | |
@Override | |
public void run() { | |
System.out.println("Waiting on thread 2."); | |
reentrantLock.lock(); | |
System.out.println("Acquiring from thread 2."); | |
reentrantLockDemo.checkSync(); | |
reentrantLock.unlock(); | |
} | |
}); | |
Thread t3 = new Thread(new Runnable() { | |
@Override | |
public void run() { | |
try { | |
System.out.println("Waiting on thread 3."); | |
reentrantLock.lockInterruptibly(); | |
System.out.println("Acquiring from thread 3."); | |
reentrantLockDemo.checkSync(); | |
reentrantLock.unlock(); | |
} catch (InterruptedException e) { | |
e.printStackTrace(); | |
} | |
} | |
}); | |
System.out.println("I am thread 1: " + t1.getName()); | |
System.out.println("I am thread 2: " + t2.getName()); | |
System.out.println("I am thread 3: " + t3.getName()); | |
t1.start(); | |
Thread.sleep(500); | |
t2.start(); | |
t3.start(); | |
// t2.interrupt(); | |
t3.interrupt(); | |
System.out.println("Interrupted."); | |
t1.join(); | |
t2.join(); | |
t3.join(); | |
System.out.println(reentrantLock.toString()); | |
System.out.println("Finished.."); | |
} | |
private void checkSync() { | |
System.out.println("Acquired.." + reentrantLock.toString()); | |
long count = 0; | |
for (int i=0; i< Integer.MAX_VALUE ; i++) { | |
count += i; | |
} | |
System.out.println("Done.."); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment