簡單的守護線程demo

/**
 * 守護線程
 */
static class Daemon implements Runnable {
   List<Runnable> tasks = new ArrayList<Runnable>();
   private Thread thread;
   private int time;

   public Daemon(Thread r, int t) {
      thread = r;
      time = t;
   }

   public void addTask(Runnable r) {
      tasks.add(r);
   }

   @Override
   public void run() {
      while (true) {
         try {
            Thread.sleep(time * 1000);
         } catch (InterruptedException e) {
            e.printStackTrace();
         }
         thread.interrupt();
      }
   }

}

調用:

//任務線程
Thread t = new Thread(runnable);
//守護線程
Daemon daemon = new Daemon(t, 120);//120秒超時時間
Thread daemoThread = new Thread(daemon);
daemoThread.setDaemon(true);
//執行這兩個線程
t.start();
daemoThread.start();

發佈了43 篇原創文章 · 獲贊 11 · 訪問量 6萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章