在java中创建后台线程的最佳方法

编程入门 行业动态 更新时间:2024-10-09 22:22:31
本文介绍了在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中创建后台线程的最佳方法

本文发布于:2023-11-28 06:35:22,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1641313.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:线程   后台   方法   java

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!