alarm.java

来自「JAVA网络编程技术内幕一书的源代码」· Java 代码 · 共 54 行

JAVA
54
字号
/* * Java Network Programming, Second Edition * Merlin Hughes, Michael Shoffner, Derek Hamner * Manning Publications Company; ISBN 188477749X * * http://nitric.com/jnp/ * * Copyright (c) 1997-1999 Merlin Hughes, Michael Shoffner, Derek Hamner; * all rights reserved; see license.txt for details. */public class Alarm implements Runnable {
  public Alarm (int time, Alarmable target) {
    this (time, target, null);
  }

  protected Alarmable target;
  protected Object arg;
  protected int time;
  public Alarm (int time, Alarmable target, Object arg) {
    this.time = time;
    this.target = target;
    this.arg = arg;
  }

  protected Thread alarm;
  public synchronized void start () {
    if (alarm == null) {
      alarm = new Thread (this);
      alarm.start ();
    }
  }

  public synchronized void stop () {
    if (alarm != null) {
      alarm.interrupt ();
      alarm = null;
    }
  }

  public void run () {
    try {
      Thread.sleep (time);
      synchronized (this) {
        if (Thread.interrupted ())
          return;
        alarm = null;
      }
      target.alarmCall (arg);
    } catch (InterruptedException ignored) {
    }
  }
}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?