java 线程自运行类

来源:互联网 发布:mongodb golang doc 编辑:程序博客网 时间:2024/05/18 00:09

public class InnerSelfRun extends Object {
 private Thread internalThread;
 private volatile boolean noStopRequested;

 public InnerSelfRun() {
  // other constructor stuff should appear here first ...
  System.out.println("in constructor - initializing...");

  // just before returning, the thread should be created and started.
  noStopRequested = true;

  Runnable r = new Runnable() {        //内嵌了一个Runnable
    public void run() {
     try {
      runWork();
     } catch ( Exception x ) {
      // in case ANY exception slips through
      x.printStackTrace();
     }
    }
   };

  internalThread = new Thread(r);     //获取当前进程,使之运行
  internalThread.start();
 }

 private void runWork() {
  while ( noStopRequested ) {
   System.out.println("in runWork() - still going...");

   try {
    Thread.sleep(700);
   } catch ( InterruptedException x ) {
    // Any caught interrupts should be habitually re-asserted
    // for any blocking statements which follow.
    Thread.currentThread().interrupt(); // re-assert interrupt
   }
  }
 }

 public void stopRequest() {
  noStopRequested = false;
  internalThread.interrupt();
 }

 public boolean isAlive() {
  return internalThread.isAlive();
 }
}
 

原创粉丝点击