如何创建守护程序线程?什么? [英] How to create a daemon thread? and what for?

查看:106
本文介绍了如何创建守护程序线程?什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法理解守护程序线程的用法和用途。

I cannot understand the usage and the purpose of daemon threads.

它们用于什么?我该如何使用它们?
另外,我试图创建守护进程,但我不能。

What are they for? How can I use them? Also, I tried to create daemons but I couldn't.

class Evil implements Runnable {
    public static void main(String[] arg) throws Exception {
        Thread t = new Thread(new Evil());
        t.start();
        Thread.sleep(1000);
        t.setDaemon(true);//no success, error!
    }

    public void run() {
        try {
            Thread.sleep(1000);
            System.out.println("How would it be Evil!?");
            Thread.sleep(1000);
        } catch (Exception e) {
        }
    }
}

这是我到目前为止所尝试的,但它无法正常工作。

This is what I attempted so far, but it's not working properly.

推荐答案

首先你需要设置一个线程作为守护进程就在你开始之前,所以第一件事就是这样:

First you need to set a thread as daemon just before you start it, so the first thing would be like this:

 Thread t = new Thread(new Evil());
 t.setDaemon(true);//success is here now
 t.start();
 Thread.sleep(1000);

守护程序线程与普通(用户)线程类似,但存在很大差异。当没有用户线程存在(活动)时,JVM会杀死(暂停)应用程序,换句话说,如果你有1个用户线程(例如主线程)和1000个守护程序线程,那么JVM会在你的应用程序中看到一个线程,并且它会在主线程完成其工作之后杀死应用程序。

Daemon threads are like normal (user) threads, but there is a big difference. The JVM kills (halt) the application when there is no user thread exist (alive), in other word if you have 1 user thread (main thread for example) and 1000 daemon threads, here the JVM sees one thread in your application, and it kills the application just after that main thread finishes its job.

这些线程适合在后台处理或执行某些业务逻辑,直到其他用户线程处于活动状态,并提防关于使用守护程序线程更改任何内容,因为在通过JVM暂停线程之前没有任何信号。

These threads are good for handling or doing some business logic in the background till other user threads alive, and beware about changing anything withing daemon thread, because there is no any signal before halting a thread by JVM.

所以在你的情况下,守护程序线程等待1秒并说出一些东西再次睡眠1秒,因为这是守护进程,1秒后主线程不再,然后守护程序线程永远不会到达第二个睡眠线。

So in you case, where daemon thread waits for 1 second and say something and again sleep for 1 second, because this is daemon, and main threads is no more after 1 second, then daemon thread never reaches the second sleep line.

(图表)也可能对您有所帮助。

This (diagram) may help you too.

这篇关于如何创建守护程序线程?什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆