在java中创建后台线程的最佳方法 [英] Best way to create a background thread in java

查看:162
本文介绍了在java中创建后台线程的最佳方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

创建后台线程的最佳方法是每15分钟运行一次以从数据库中获取数据?

What is the best way to create a background thread that will run every 15 minutes to get the data from the database?

以下是我所拥有的代码工作正常,我猜在生产中,但有没有其他更好的方法,或者我应该注意的事情?

Below is the code I have which will work fine I guess in production but is there any other way better that I have or something that I should be aware of?

private static void checkDatabaseEveryXMinutes() {
    new Thread() {
        public void run() {
            while (true) {
                try {
                    Thread.sleep(checkingAfterEveryXMinutes);
                    getDataFromDatabase();
                } catch (InterruptedException ex) {
                    //log here
                } catch (Exception e) {
                    //log here
                }
            }
        }
    }.start();
}

使用上述代码有什么不利之处。 ScheduledExecutorService与TimerTask的比较如何?

Is there any disadvantage in using the above code. And how does ScheduledExecutorService compares with TimerTask?

哪种方式更好?

我的代码的任何示例基础都将如果有更好的方法,请对此表示赞赏。

Any example basis on my code will be appreciated on this if there are any better approach.

推荐答案

ScheduledExecutorService将返回一个Future,它有一个额外的方法来检查是否Runnable完成了。两者都有取消Runnable的方法。对于像这样的重复任务,检查它是否已完成,可能不会有多大用处。但是,它是用jdk 1.5并发api引入的,它绝对应该用来代替旧的并发/线程api(Timer和TimerTask是jdk 1.3)。它们将更强大,性能更好。它们与java doc中的用例有一个非常相似的例子这里

ScheduledExecutorService will return you a Future that has an additional method to check if the Runnable completed. Both have methods for canceling the Runnable. For repeated task like this, checking if it's done, is probably not going to be of much use. However, it was introduced with jdk 1.5 concurrency api, which should definitely be used in place of older concurrency/thread api's (Timer and TimerTask were jdk 1.3). They will be more robust, and better performant. They have a very similar example as your use case in the java doc here.

这里是一个样本:

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;

public class ScheduledTaskExample {
    private final ScheduledExecutorService scheduler = Executors
        .newScheduledThreadPool(1);

    public void startScheduleTask() {
    /**
    * not using the taskHandle returned here, but it can be used to cancel
    * the task, or check if it's done (for recurring tasks, that's not
    * going to be very useful)
    */
    final ScheduledFuture<?> taskHandle = scheduler.scheduleAtFixedRate(
        new Runnable() {
            public void run() {
                try {
                    getDataFromDatabase();
                }catch(Exception ex) {
                    ex.printStackTrace(); //or loggger would be better
                }
            }
        }, 0, 15, TimeUnit.MINUTES);
    }

    private void getDataFromDatabase() {
        System.out.println("getting data...");
    }

    public void shutdowh() {
        System.out.println("shutdown...");
        if(scheduler != null) {
            scheduler.shutdown();
        }
    }

    public static void main(String[] args) {
        final ScheduledTaskExample ste = new ScheduledTaskExample();
        Runtime.getRuntime().addShutdownHook(new Thread() {
            public void run() {
                ste.shutdowh();
            }
        });
        ste.startScheduleTask();

    }
}

这篇关于在java中创建后台线程的最佳方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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