相当于Python线程守护程序模式的Java线程

时间:2019-04-03 08:22:34

标签: java multithreading

在python中,我可以将一个线程设置为守护程序,这意味着如果父线程死亡,则子线程会自动与其一起死亡。

Java是否有等效功能?

当前,我正在Java中启动一个这样的线程,但是即使主线程退出,底层的子线程也不会死机并挂起

         executor = Executors.newSingleThreadExecutor();
         executor.submit(() -> {
             while (true) {
                 //Stopwatch stopwatch = Stopwatch.createStarted();

                 String threadName = Thread.currentThread().getName();
                 System.out.println("Hello " + threadName);
                 try {
                     Thread.sleep(1*1000);
                 } catch (InterruptedException e) {
                     break;
                 }   

             }       
         });

1 个答案:

答案 0 :(得分:1)

与裸露的Thread互动时,您可以使用:

Thread thread = new Thread(new MyJob());
thread.setDaemon(true);

thread.start();

在您的示例中,需要为ExecutorService提供ThreadFactoryExecutors.newSingleThreadExecutor(new ThreadFactory() { @Override public Thread newThread(Runnable r) { Thread thread = new Thread(r); thread.setDaemon(true); return thread; } }); 应该执行类似的工作-像这样:

Guava

我还建议使用ThreadFactoryBuilder s Executors.newSingleThreadExecutor( new ThreadFactoryBuilder() .setDaemon(true) .build() );

def move():
  global score
  last = snake[-1]
  first = snake[0]
  next = list(last)
  remove = True

  if direction == "right":
    if last[0] + 1 == 8:
     next[0] = 0
    else:
     next[0] = last[0] + 1
  elif direction == "left":
    if last[0] - 1 == -1: 
      next[0] = 7
    else:
      next[0] = last[0] - 1

  elif direction == "down":
    if last[1] + 1 == 8: 
      next[1] = 0
    else:
      next[1] = last[1] + 1

  elif direction == "up":
    if last[1] - 1 == -1: 
      next[1] = 7
    else:
      next[1] = last[1] - 1

  if next in vegetables: 
    vegetables.remove(next)
    score += 1

  if remove = True:
    sense.set_pixel(first[0], first[1], blank)
    slug.remove(first)
    if next in vegetables:
      if score % 1 == 0:
        remove = False
        pause = pause * 8

  snake.append(next)
  sense.set_pixel(next[0], next[1], green)
  sense.set_pixel(first[0], first[1], blank)
  snake.remove(first)

它简化了设置最常见的线程属性的过程,并允许链接多个线程工厂

更新

正如蜘蛛Slaw和Boris正确注意到的那样-您已经提到了当父线程死亡时可能导致杀死子线程的行为。在Python或Java中没有类似的东西。当所有其他非守护程序线程退出时,守护程序线程将被杀死。