只要守护程序线程正在运行,如何使我的程序保持活动状态? [英] How to keep my program alive for as long a daemon thread is running?

查看:100
本文介绍了只要守护程序线程正在运行,如何使我的程序保持活动状态?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个要求,我想启动一个轮询器一次,该轮询器将永远运行直到重新启动计算机或该进程被终止为止。现在,我尝试使用Shell脚本从主方法启动轮询器,但是问题是,一旦主方法完成执行,轮询器也停止工作,因为我没有使用任何服务器来实现此目的。 / p>

我听说了有关 daemon线程的一些信息,但是我想知道如何创建一个可以永久运行的守护程序线程,



更新:

  public类SomeThread扩展了线程{

@Override
public void run(){
UnitPoller unitPoller = new UnitPoller();
unitPoller.doPolling();
}

public static void main(String [] args){
SomeThread someThread = new SomeThread();
someThread.setDaemon(true);
someThread.start();
}
}

以上是我的更新类,现在无论何时执行此操作main方法中的线程创建线程,但是一旦main方法执行完成,我的轮询器就会停止工作,因为JVM关闭。



出现此问题,我该怎么办。



谢谢

解决方案

您只需创建线程并在调用 th.start()之前调用 th.setDaemon(true)



编辑:



以上内容回答了如何创建守护线程的问题,但是(由于问题的范围已更改, ),正确的答案是:如果您希望线程在主线程完成后阻止JVM退出,请不要创建守护进程线程。


I have a requirement, that I want to start a poller once which will run foreever until the machine is restarted or the process is being killed. Now, I tried to start the poller from a main method using a shell script, but the problem is that as soon as the main method completed its execution, the poller also stoped working, as i am not using any servers to achieve so.

I heard something about daemon threads, but I am wondering how to create a daemon thread, which will run forever, and help my poller to run also.

UPDATE:

public class SomeThread extends Thread {

    @Override
    public void run() {
        UnitPoller unitPoller = new UnitPoller();
        unitPoller.doPolling();
    }

    public static void main(String[] args) {
        SomeThread someThread = new SomeThread();
        someThread.setDaemon(true);
        someThread.start();
    }
}

Above is my updated class, now whenever I execute this thread from the main method, it creates a thread but as soon as the execution of main method completes, my poller stops working, as the JVM shuts down.

With this problem, what should i do.

Thanks

解决方案

You just create a thread and call th.setDaemon(true) before calling th.start().

Edit:

The above answers the question "how to create a daemon thread", but (as the scope of the question has changed), a proper answer would be: don't create a daemon thread if you want your thread to keep the JVM from exiting once the main thread completed.

这篇关于只要守护程序线程正在运行,如何使我的程序保持活动状态?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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