Java ReentrantLock extend

Description

Java ReentrantLock extend

import java.util.Collection;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

class MyLock extends ReentrantLock {
  public String getOwnerName() {
    if (this.getOwner() == null) {
      return "Owner name is NULL";
    }/* w  w w  .ja  v  a2  s . c  om*/
    return this.getOwner().getName();
  }
  public Collection<Thread> getThreads() {
    return this.getQueuedThreads();
  }
}

class Task implements Runnable {
  private Lock lock;

  public Task(Lock lock) {
    this.lock = lock;
  }

  @Override
  public void run() {
    for (int i = 0; i < 5; i++) {
      lock.lock();
      System.out.println("Lock:"+ Thread.currentThread().getName());
      try {
        TimeUnit.MILLISECONDS.sleep(500);
        System.out.println("Free Lock:"+ Thread.currentThread().getName());
      } catch (InterruptedException e) {
        e.printStackTrace();
      } finally {
        lock.unlock();
      }
    }
  }
}

public class Main {
  public static void main(String[] args) throws Exception {
    MyLock lock = new MyLock();
    Thread threads[] = new Thread[5];
    for (int i = 0; i < 5; i++) {
      Task task = new Task(lock);
      threads[i] = new Thread(task);
      threads[i].start();
    }
    for (int i = 0; i < 15; i++) {
      System.out.printf("Owner : %s\n", lock.getOwnerName());
      System.out.printf("Queued Threads: %s\n", lock.hasQueuedThreads());
      if (lock.hasQueuedThreads()) {
        System.out.printf("Queue Length: %d\n", lock.getQueueLength());
        System.out.printf("Queued Threads: ");
        Collection<Thread> lockedThreads = lock.getThreads();
        for (Thread lockedThread : lockedThreads) {
          System.out.printf("%s ", lockedThread.getName());
        }
        System.out.println();
      }
      System.out.printf("Lock: Fairness: %s\n", lock.isFair());
      System.out.printf("Lock: Locked: %s\n", lock.isLocked());

      TimeUnit.SECONDS.sleep(1);
    }
  }
}



PreviousNext

Related