Advertisement
Guest User

Untitled

a guest
Mar 25th, 2019
64
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.71 KB | None | 0 0
  1. public static void main(String[] args) throws Exception {
  2.     final ReentrantLock lock1 = new ReentrantLock();
  3.     final ReentrantLock lock2 = new ReentrantLock();
  4.     Runnable try1_2 = getRunnable(lock1, "lock 1", lock2, "lock 2");
  5.     Runnable try2_1 = getRunnable(lock2, "lock 2", lock1, "lock 1");
  6.     new Thread(try1_2).start();
  7.     new Thread(try2_1).start();
  8. }
  9.  
  10. private static Runnable getRunnable(final ReentrantLock lock1, final String lock1Name, final ReentrantLock lock2, final String lock2Name) {
  11.     return new Runnable() {
  12.         @Override
  13.         public void run() {
  14.             try {
  15.                 if (lock1.tryLock(1, TimeUnit.SECONDS)) {
  16.                     System.out.println(lock1Name + " acquired in thread " + Thread.currentThread());
  17.                     if (lock2.tryLock(1, TimeUnit.SECONDS)) {
  18.                         System.out.println(lock2Name + " acquired in thread " + Thread.currentThread());
  19.                         Thread.sleep(2000);
  20.                     } else {
  21.                         System.out.println("Could not acquire "+lock2Name + " in thread " + Thread.currentThread());
  22.                         lock1.unlock();
  23.                         System.out.println(lock1Name + " released in thread " + Thread.currentThread());
  24.                     }
  25.                 } else {
  26.                     System.out.println("Could not acquire " + lock1Name + " in thread " + Thread.currentThread());
  27.                 }
  28.             } catch (InterruptedException e) {
  29.                 //you should not ignore it
  30.             } finally {
  31.                 if (lock1.isHeldByCurrentThread()) lock1.unlock();
  32.                 if (lock2.isHeldByCurrentThread()) lock2.unlock();
  33.             }
  34.         }
  35.     };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement