Java通知线程已运行结束

走着路睡觉
  • java
小于 1 分钟

通知接口,实现该接口,处理线程结束通知

public interface ThreadCompleteListener {
    void notifyOfThreadComplete(final Thread thread);
}

demo

public abstract class NotifyingThread extends Thread {
  private final Set<ThreadCompleteListener> listeners
                   = new CopyOnWriteArraySet<ThreadCompleteListener>();
  //增加监听器
  public final void addListener(final ThreadCompleteListener listener) {
    listeners.add(listener);
  }
  //移除监听器
  public final void removeListener(final ThreadCompleteListener listener) {
    listeners.remove(listener);
  }
  private final void notifyListeners() {
    for (ThreadCompleteListener listener : listeners) {
      listener.notifyOfThreadComplete(this);
    }
  }
  @Override
  public final void run() {
    try {
      doRun();
    } finally {
      notifyListeners();
    }
  }
  // 新建类重写该方法
  public abstract void doRun();
}
上次编辑于:
贡献者: zhaojingbo
Loading...