简体   繁体   English

Thread.sleep()无法连续工作

[英]Thread.sleep() doesn't work continously

I have a program to read some RSS feeds, parse them, and copy the links somewhere else. 我有一个程序可以读取一些RSS feed,对其进行解析,然后将链接复制到其他位置。 Well! 好! I want to check the RSS feeds about every 10 minutes for probable updates. 我想大约每10分钟检查一次RSS提要,以获取可能的更新。 I wrote this piece of code: 我写了这段代码:

   @Override
public void run() {
    while (true) {
        // check feeds here
        try {
            Thread.sleep(600000);
        } catch (InterruptedException ex) {
            // exception handing
        }
    }
}

When I run it, for a day or two, it's OK and running. 运行一两天后,就可以正常运行了。 But usually after 3 or 4 days, it goes to sleep and never wakes up again!!! 但是通常在3或4天后,它会进入睡眠状态,再也不会醒来!!! So it doesn't update the RSS feeds. 因此,它不会更新RSS提要。

How can I solve this issue!? 我该如何解决这个问题!

If I have to guess I would say there's probably a bug in the code that reads the feeds which raises an unhandled exception which in turn ends the thread. 如果我不得不猜测,我会说读取提要的代码中可能存在一个错误,该错误会引发未处理的异常,从而导致线程结束。 To you it seems like the thread never wakes, when in fact it dies. 对您来说,线程似乎永不唤醒,而实际上它却死了。

public void run() {
    while (true) {
        // check feeds here   <<<---- Look for the bug here
        try {
            Thread.sleep(600000);
        } catch (InterruptedException ex) {
            // exception handing
        }
    }
}

It's very unlikely that there's a bug in the Thread.sleep method (as it is widely use almost everywhere). Thread.sleep方法中几乎没有错误(因为它在几乎所有地方都被广泛使用)。 Anyway, debug and check to see if your thread is still alive or if it has died. 无论如何,请调试并检查线程是否仍处于活动状态或是否已终止。

Try the java executor libraries. 尝试使用Java执行程序库。 They were introduced in java 5 and make this sort of code more efficient and cleaner. 它们是在Java 5中引入的,它们使这种代码更加有效和简洁。

ScheduledExecutorService es = Executors.newScheduledThreadPool(1);
es.schedule(new Runnable(){
    @Override
    public void run() {
        //RSS checking
    }
}, 10, TimeUnit.MINUTES);

There is a lot going on in these libraries so it is worth checking them out. 这些库中发生了很多事情,因此值得一试。

Perhaps it is stopping because of memory or something like this. 也许是由于内存或类似的东西而停止了。 Try the method above to check every 10 minutes. 请尝试上述方法每10分钟检查一次。

There is also the concept of Callable (instead of Runnable) which allows throwing exceptions which may help you debug this. 还有Callable(而不是Runnable)的概念,它允许引发异常,这可以帮助您调试此异常。 You get a future object returned which you can use to help. 您将获得一个将来的对象,可以用来帮助您。 This link looks quite good http://www.javacodegeeks.com/2011/09/java-concurrency-tutorial-callable.html 该链接看起来非常不错http://www.javacodegeeks.com/2011/09/java-concurrency-tutorial-callable.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM