04-案例实现
案例实现
根据以下步骤实现本案例。
1.创建 MyLock
类,该类继承了 ReentrantLock
:
public class MyLock extends ReentrantLock {
2.实现 getOwnerName()
方法。在该方法内部,通过 Lock
类上的protected方法 getOwner()
获得当前持有锁线程的名称(如果有的话):
public String getOwnerName() {
if (this.getOwner()==null) {
return "None";
}
return this.getOwner().getName();
}
3.实现 getThreads()
方法。在该方法内部,通过 Lock
类中的protected方法 getQueuedThreads()
获得当前在锁上排队的所有线程列表:
public Collection<Thread> getThreads() {
return this.getQueuedThreads();
}
4.创建 Task
类,该类实现了 Runnable
接口:
public class Task implements Runnable {
5.声明一个 Lock
类型的私有属性 lock
:
private final Lock lock;
6.在类的构造函数中完成属性的初始化:
public Task (Lock lock) {
this.lock=lock;
}
7.实现 run()
方法,在该方法内部完成5次循环:
@Override
public void run() {
for (int i=0; i<5; i++) {
8.使用 lock()
方法获得锁,并输出信息到控制台中:
lock.lock();
System.out.printf("%s: Get the Lock.\n",
Thread.currentThread().getName());
9.让线程休眠500ms,用 unlock()
方法释放锁并在控制台上打印消息:
try {
TimeUnit.MILLISECONDS.sleep(500);
System.out.printf("%s: Free the Lock.\n",
Thread.currentThread().getName());
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
}
}
10.实现本案例的主类,新建 Main
类和 main()
方法:
public class Main {
public static void main(String[] args) throws Exception {
11.创建一个 MyLock
类型的变量 lock
:
MyLock lock=new MyLock();
12.创建一个能够容纳5个 Thread
对象的数组:
Thread threads[]=new Thread[5];
13.分别启动这5个线程并执行 Task
对象:
for (int i=0; i<5; i++) {
Task task=new Task(lock);
threads[i]=new Thread(task);
threads[i].start();
}
14.创建一个包含15步的循环:
for (int i=0; i<15; i++) {
15.把锁的所有者的名称输出到控制台中:
System.out.printf("Main: Logging the Lock\n");
System.out.printf("************************\n");
System.out.printf("Lock: Owner : %s\n",lock.getOwnerName());
16.显示当前正在排队等待锁的线程数量和名称:
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");
}
17.显示关于 Lock
对象的公平性和状态的信息:
System.out.printf("Lock: Fairness: %s\n",lock.isFair());
System.out.printf("Lock: Locked: %s\n",lock.isLocked());
System.out.printf("************************\n");
18.让线程休眠1s并关闭循环和类:
TimeUnit.SECONDS.sleep(1);
}
}
}