锁接口是 Java Concurrency API 提供以获得一个代码块的同步的基本机制之一。 它可以定义一个临界区。临界区是一个访问共享资源的代码块,同一时间不能被多于一个线程执行。 此机制由 Lock 接口和 ReentrantLock 类实现。
在本节中,将学习能获得关于锁对象的什么信息以及如何获得那些信息。
本节的示例代码在 com.elanzone.books.noteeg.chpt8.sect02 package中
MyLock 类 : extends ReentrantLock
public String getOwnerName() { if (this.getOwner() == null) { return "None"; } return getOwner().getName(); }
public Collection<Thread> getThreads() { return this.getQueuedThreads(); }
Runnable 实现类 : 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.printf("%s: Get the Lock.\n", Thread.currentThread().getName()); try { TimeUnit.MILLISECONDS.sleep(500); System.out.printf("%s: Free the Lock.\n", Thread.currentThread().getName()); } catch (InterruptedException e) { e.printStackTrace(); } finally { lock.unlock(); } } }
控制类: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("Main: Logging the Lock\n"); System.out.printf("************************\n"); System.out.printf("Lock: Owner : %s\n", lock.getOwnerName()); System.out.printf("Lock: Queued Threads: %s\n", lock.hasQueuedThreads()); if (lock.hasQueuedThreads()) { System.out.printf("Lock: Queue Length: %d\n", lock.getQueueLength()); System.out.printf("Lock: Queued Threads: "); Collection<Thread> lockedThreads = lock.getThreads(); for (Thread lockedThread : lockedThreads) { System.out.printf("%s ", lockedThread.getName()); } System.out.printf("\n"); } System.out.printf("Lock: Fairness: %s\n", lock.isFair()); System.out.printf("Lock: Locked: %s\n", lock.isLocked()); System.out.printf("************************\n"); TimeUnit.SECONDS.sleep(1); } }
在本节中,MyLock 类扩展 ReentrantLock 类来返回信息。不扩展的话返回不了,因为数据是 ReentrantLock 类的 protected 数据。 由 MyLock 类实现的方法有:
我们也用了其他的在 ReentrantLock 类中实现的一些方法: