Java while循环和线程! [英] Java while loop and Threads!

查看:295
本文介绍了Java while循环和线程!的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个程序不断轮询数据库以查看某些字段值的变化。它在后台运行,目前使用while(true)和sleep()方法来设置间隔。我想知道这是一个好习惯吗?而且,实现这一目标的更有效方法是什么?该程序应始终运行。

I have a program that continually polls the database for change in value of some field. It runs in the background and currently uses a while(true) and a sleep() method to set the interval. I am wondering if this is a good practice? And, what could be a more efficient way to implement this? The program is meant to run at all times.

因此,停止程序的唯一方法是对进程ID发出kill。该程序可能处于JDBC调用的中间。我怎么能更优雅地终止它呢?我知道最好的选择是通过使用将由线程定期检查的标志来设计某种退出策略。但是,我无法想到改变这个标志值的方式/条件。有什么想法?

Consequently, the only way to stop the program is by issuing a kill on the process ID. The program could be in the middle of a JDBC call. How could I go about terminating it more gracefully? I understand that the best option would be to devise some kind of exit strategy by using a flag that will be periodically checked by the thread. But, I am unable to think of a way/condition of changing the value of this flag. Any ideas?

推荐答案


我想知道这是不是一个好习惯?

I am wondering if this is a good practice?

不。这不好。有时候,这就是你所拥有的一切,但它并不好。

No. It's not good. Sometimes, it's all you've got, but it's not good.


而且,实现这一目标可能是一种更有效的方式? / p>

And, what could be a more efficient way to implement this?

首先如何进入数据库?

How do things get into the database in the first place?

最好的改变是修复插入/更新数据库的程序,以发出进入数据库和程序的请求。 JMS主题适用于此类事情。

The best change is to fix programs that insert/update the database to make requests which go to the database and to your program. A JMS topic is good for this kind of thing.

下一个最佳更改是向数据库添加触发器,以将每个插入/更新事件排入队列。队列可以提供JMS主题(或队列)以供程序处理。

The next best change is to add a trigger to the database to enqueue each insert/update event into a queue. The queue could feed a JMS topic (or queue) for processing by your program.

回退计划是您的轮询循环。

The fall-back plan is your polling loop.

但是,您的轮询循环不应该做很多工作。它应该将消息放入队列以供其他JDBC进程处理。终止请求是可以放入JMS队列的另一条消息。当您的程序获得终止消息时,绝对必须使用先前的JDBC请求完成并且可以正常停止。

Your polling loop, however, should not trivially do work. It should drop a message into a queue for some other JDBC process to work on. A termination request is another message that can be dropped into the JMS queue. When your program gets the termination message, it absolutely must be finished with the prior JDBC request and can stop gracefully.

在执行任何此操作之前,请查看ESB解决方案。 Sun的 JCAPS TIBCO 已经有了这个。一个开源的ESB,如 Mulesource Jitterbit 可能已经构建并测试了此功能。

Before doing any of this, look at ESB solutions. Sun's JCAPS or TIBCO already have this. An open source ESB like Mulesource or Jitterbit may already have this functionality already built and tested.

这篇关于Java while循环和线程!的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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