这样做的目的是:
我有一个主类,在这个类中,我想创建一个线程。该线程必须每10分钟返回一次数据(我知道正常线程实现是不可能的)。
我看到了一些关于可调用或ScheduledExecuter的实现,但是我无法适应它。
我需要它,因为在程序执行期间,我的数据库正在更新。所以我想要一个每10分钟执行一次查询并返回结果的线程。
谢谢。
发布于 2014-04-07 12:35:22
一个简单的可调用的解决方案
interface Callable {
void call(Data d);
}
class MyThread implements Runnable{
Callable callable;
public MyThread(Callable c){
callable = c;
}
void run(){
while(true){
callable.call(/** pass your data */);
//sleep 10 minutes
}
}
}现在可以从代码中创建MyThread对象,并将其传递给可调用的对象。您可以使用匿名类来完成这一任务。
MyThread t = new MyThread(new Callable(){
void call(Data d){
//process data here
}
});发布于 2014-04-07 12:40:38
当您希望定期安排要发生的事情时,可以使用一个或多个java.util.Timer和一个或多个java.util.TimerTask。
但是,无论您使用计时器还是使用自己的线程实现自己的时间调度,您都需要通过线程/TimerTask与主线程中的对象进行通信。您可以通过将这些对象传递给这些线程,然后在运行方法中调用它们上的方法来实现这一点。但是请记住,当从子线程调用该方法时,您无法控制主线程正在做什么。有时,当主线程执行某些操作时,子线程会更改一个值。这可能导致奇怪的bug,通常被称为种族条件。举个例子:
class ValueList {
private List<Integer> values = new ArrayList<>();
// this method may be called from many different threads to add values
public void add(Integer i) {
values.add(i);
}
// this method is called from the main thread to update the GUI
public int getAverage() {
int sum = 0;
for (Integer i: values) {
sum += i;
}
// Imagine a thread calls add(Integer) when the main threads
// execution is exactly here!
// the average will be too low because the new value was
// not yet counted for the sum, but is now accounted for
// when calculating the average from the sum.
return sum / values.size();
}
}要防止这种情况发生,请熟悉Java提供的各种同步特性。
发布于 2014-04-07 12:37:12
线程都存在于父进程的相同内存空间中,因此在线程之间传递数据实际上非常简单。这样做的最基本方法是简单地覆盖一个公共内存位置,(比如两个线程都知道的公共对象中的一个字符串),尽管不是很好的实践。
在执行多线程数据时,您需要小心语义,因为在实现多线程应用程序时引入争用条件和其他各种缺点是一个常见的错误。
仅举一个例子:http://en.wikipedia.org/wiki/Producer-consumer_problem
查看java.lang.concurrency类可能会让您了解如何在线程之间安全地传递数据,但请考虑到这是计算机科学的一个相当复杂的领域,并适当地规划学习时间:http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/package-tree.html。
https://stackoverflow.com/questions/22912406
复制相似问题