Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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