java 如何创建守护线程?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1276865/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 15:54:49  来源:igfitidea点击:

How do I create daemon threads?

javadaemon

提问by Biju CD

Can a java programmer can create daemon threads manually? How is it?

java程序员可以手动创建守护线程吗?如何?

回答by Michael Borgwardt

java.lang.Thread.setDaemon(boolean)

java.lang.Thread.setDaemon(boolean)

Note that if not set explicitly, this property is "inherited" from the Thread that creates a new Thread.

请注意,如果未明确设置,则此属性将从创建新线程的线程“继承”。

回答by amoran

You can mark a thread as a daemon using the setDaemon method provided. According to the java doc:

您可以使用提供的 setDaemon 方法将线程标记为守护进程。根据java文档:

Marks this thread as either a daemon thread or a user thread. The Java Virtual Machine exits when the only threads running are all daemon threads.

This method must be called before the thread is started.

This method first calls the checkAccess method of this thread with no arguments. This may result in throwing a SecurityException (in the current thread).

将此线程标记为守护线程或用户线程。当唯一运行的线程都是守护线程时,Java 虚拟机退出。

这个方法必须在线程启动之前调用。

该方法首先不带参数调用该线程的 checkAccess 方法。这可能会导致抛出 SecurityException(在当前线程中)。

Here an example:

这里有一个例子:

Thread someThread = new Thread(new Runnable() {
    @Override
    public void run() {
        runSomething();
    }
});
someThread.setDaemon(true);
someThread.start();

回答by Rohit

class mythread1 implements Runnable {
  public void run() {
    System.out.println("hii i have set thread as daemon");
  }


  public static void main(String []arg) {
    mythread1 th=new mythread1();
    Thread t1 = new Thread(th);
    t1.setDaemon(true);
    t1.start();
    System.out.println(t1.isDaemon());
  }
}

回答by Lliane

Yes you can

是的你可以

Thread thread = new Thread(  
  new Runnable(){  
    public void run(){  
      while (true)
        wait_for_action();
    }  
  }  
);  
thread.start();