当前位置:嗨网首页>书籍在线阅读

20-案例实现

  
选择背景色: 黄橙 洋红 淡粉 水蓝 草绿 白色 选择字体: 宋体 黑体 微软雅黑 楷体 选择字体大小: 恢复默认

案例实现

根据如下步骤实现本案例。

1.创建 Task 类并实现 Runnable 接口:

public class Task implements Runnable {

2.声明一个私有的 Semaphore 属性,并将其命名为 semaphore

private final Semaphore semaphore;

3.实现构造器来初始化该属性:

public Task(Semaphore semaphore){
  this.semaphore=semaphore;
}

4.实现 run() 方法。首先获取 semaphore 属性的许可,获取成功后打印一条消息:

@Override
public void run() {
  try {
    semaphore.acquire();
    System.out.printf("%s: Get the semaphore.\n",
                      Thread.currentThread().getName());

5.用 sleep() 方法让线程休眠2s。然后,释放许可并打印一条信息:

  TimeUnit.SECONDS.sleep(2);
  System.out.println(Thread.currentThread().getName()+":
                     Release the semaphore.");
} catch (InterruptedException e) {
  e.printStackTrace();
} finally {
  semaphore.release();
}

6.实现本案例的主类。创建 Main 并添加 main() 方法:

public class Main {
  public static void main(String[] args) throws Exception {

7.创建包含3个许可的 Semaphore 对象,并将其命名为 semaphore

Semaphore semaphore=new Semaphore(3);

8.创建一个容纳10个 Thread 对象的数组:

Thread threads[]=new Thread[10];

9.创建并启动10个 Thread 来执行10个 Task 。每当启动一个线程后,让主线程休眠200ms,然后再调用 showLog() 方法打印 semaphore 的信息:

for (int i=0; i<threads.length; i++) {
  Task task=new Task(semaphore);
  threads[i]=new Thread(task);
  threads[i].start();
  TimeUnit.MILLISECONDS.sleep(200);
  showLog(semaphore);
}

10.实现一个5次的循环,调用 showLog() 方法打印有关 semaphore 的信息,并让主线程休眠1s:

  for (int i=0; i<5; i++) {
    showLog(semaphore);
    TimeUnit.SECONDS.sleep(1);
  }
}

11.实现 showLog() 方法。它接收一个 Semaphore 对象作为参数。向控制台打印可用许可、是否存在排队线程、排队数量,以及 semaphore 是否是先进先出的公平模式:

private static void showLog(Semaphore semaphore) {
  System.out.printf("********************\n");
  System.out.printf("Main: Semaphore Log\n");
  System.out.printf("Main: Semaphore: Avalaible Permits: %d\n",
                    semaphore.availablePermits());
  System.out.printf("Main: Semaphore: Queued Threads: %s\n",
                    semaphore.hasQueuedThreads());
  System.out.printf("Main: Semaphore: Queue Length: %d\n",
                    semaphore.getQueueLength());
  System.out.printf("Main: Semaphore: Fairness: %s\n",
                    semaphore.isFair());
  System.out.printf("********************\n");
}