一个好用的工作线程

来源:互联网 发布:淘宝的牛肉为什么便宜 编辑:程序博客网 时间:2024/05/21 10:17

import java.util.logging.Logger;

public abstract class WorkThread extends Thread {

 private boolean pause;

 private boolean shutdown;

 private Logger log = null;

 public WorkThread() {
  super();
  this.addShutdownHooker(new Thread() {
   public void run() {
    log.warning("System is shutdown,begin to do final process");
    doFinal();
   }
  });
 }

 public WorkThread(String workerName) {
  super(workerName);
  this.addShutdownHooker(new Thread() {
   public void run() {
    log.warning("System is shutdown,begin to do final process");
    doFinal();
   }
  });
 }

 public boolean isPause() {
  return pause;
 }

 public void run() {
  beforeWork();
  while (!this.isShutdown()) {
   try {
    if (!pause) {
     work();
    } else {
     log.fine("WorkThread " + getName() + " is pause");
    }
   } catch (Throwable e) {
    log
      .severe("WrokThread "
        + getName()
        + " throw uncaughtException/n[----------------Throwable----------------]/n"
        + e
        + "/n[-----------------Cause-------------------]/n"
        + e.getCause());
    e.printStackTrace();
    this.shutdown();
   }
  }
  log.warning("WorkThread " + getName() + " is shutdown");
  afterWork();
 }
 /**
  *
  *线程启动前调用此方法,主要是初始化一些运行参数
  */
 protected void beforeWork() {
 }

 /**
  *
  *线程即将退出时调用此方法,可以做一些清理工作
  */
 protected void afterWork() {
 }

 /**
  * 客户端必须实现的方法,此方法会被循环调用直到用户关闭线程或暂停线程
  * @throws InterruptedException
  */
 public abstract void work() throws InterruptedException;

 /**
  *
  *以守护线程的方式启动线程
  */
 public void startDaemon() {
  log = Logger.getLogger(getName());
  this.setDaemon(true);
  this.start();
 }

 /**
  * 当线程处于暂停状态时可以调用此方法使线程继续工作
  *
  */
 public synchronized void restart() {
  this.pause = false;
 }

 /**
  * 暂停工作
  *
  */
 public synchronized void pause() {
  this.pause = true;
 }

 /**
  * 主动关闭线程
  *
  */
 public synchronized void shutdown() {
  pause();
  this.shutdown = true;
 }

 /**
  * 判断此线程是否已经关闭
  * @return
  */
 public boolean isShutdown() {
  return shutdown;
 }

 /**
  * 当系统退出时此方法将被虚拟机运行
  *
  */
 protected void doFinal() {

 }

 /**
  *
  * 添加一个系统钩子
  * @param thread
  */
 protected void addShutdownHooker(Thread thread) {
  Runtime.getRuntime().addShutdownHook(thread);
 }

 public String toString() {
  return "WorkThread " + getName() + " [Pause = " + this.isPause()
    + " | Shutdown = " + this.isShutdown() + " | Interrupt = "
    + this.isInterrupted() + " | Alive = " + this.isAlive()
    + " | Daemon = " + this.isDaemon() + "]";
 }
}

原创粉丝点击