如何将守护程序线程分类到特定线程?

时间:2014-01-10 12:25:27

标签: java multithreading daemon

我有3个线程称为T1T2T3,还有3个守护程序线程,如dt1dt2dt3

我想(分配)向线程dt1提供服务T1,将dt2提供给线程T2,将dt3提供给线程T3 。 当线程T1T2T3完成其可运行任务时,它的相关守护程序线程也在内部关闭。

任何人都可以告诉我如何在java中使用线程守护进程概念吗?

2 个答案:

答案 0 :(得分:0)

“守护程序线程”不是一个概念 - 它只是Java线程的一个特性。当JVM终止时,它会等待非守护程序线程自行终止。相反,无论他们正在做什么,守护程序线程都会被终止。

抛弃它,一个想法可能是在你的“守护进程”线程中建立一个“关闭”标志。当非守护程序线程终止时,它可以将该标志设置为true。守护程序线程将检查该标志并在其为真后终止。请记住正确地同步该机制,例如使用volatile关键字。

答案 1 :(得分:0)

所以,如果我正确理解你的问题,你希望每个'工作线程'T1..T3有自己的后台线程(dt1 ... dt3)进行一些协同处理,并且你希望后台线程在你的时候退出主线程退出,是吗?你可以这样做:

使每个'主线程T1 ......一个看起来像这样的Runnable,这样当你启动T1时,它会启动自己的dt1,然后在完成时要求它关闭(通过interrupt())。

   @Override
   public void run() {
      ExecutorService e = Executors.newSingleThreadExecutor();
      Runnable r = new Runnable() {

         @Override
         public void run() {
            // this is your deamon thread
            boolean done = false;
            while (!done && !Thread.currentThread().isInterrupted()){
               // Do your background deamon stuff here.
               //
               // Try not to use blocking, uninterruptible methods.
               //
               /* If you call a method that throws an interrupted exception,
                * you need to catch that exception and ignore it (or set done true,)
                * so the loop will terminate. If you have other exit conditions, 
                * just set done=true in this body */
            }
         }
      };
      e.execute(r);  // launch your daemon thread

      try {
         // do your main stuff here 
      }
      finally {
         e.shutdownNow(); // this will 'interrupt' your daemon thread when run() exits.
      } 
   }