我需要通过线程&每分钟从表中读取数据,然后执行某些操作。Java中的工作线程
一旦任务完成,我应该只是启动一个线程&将其置于睡眠模式1分钟。然后再次检查表是否有任何数据,再次执行任务&进入睡眠1分钟...
这是正确的做法吗?任何人都可以为我提供一些Java代码来做同样的事情吗?
谢谢!
我需要通过线程&每分钟从表中读取数据,然后执行某些操作。Java中的工作线程
一旦任务完成,我应该只是启动一个线程&将其置于睡眠模式1分钟。然后再次检查表是否有任何数据,再次执行任务&进入睡眠1分钟...
这是正确的做法吗?任何人都可以为我提供一些Java代码来做同样的事情吗?
谢谢!
正如经常出现,从java.util.concurrent包Java 5的扩展是这里一个巨大的帮助。您可以使用ScheduledThreadPoolExecutor。这里是一个小(untestet)例如:
class ToSomethingRunnable implements Runnable {
void run() {
// Add your customized code here to update the contents in the database.
}
}
ScheduledThreadPoolExecutor executor = Executors.newScheduledThreadPool(1);
ScheduledFuture<?> future = executor.scheduleAtFixedRate(new ToSomethingRunnable(),
0, 1, TimeUnit.MINUTES);
// at some point at the end
future.cancel();
executor.shutdown();
更新:
使用一个Executor是你可以添加不同的时间间隔的许多重复任务都共享同一个线程池的简单的优点,但控制关机。
你的方法很好。你可以继续你的方法。
该样品将帮助你做你的任务:
class SimpleThread extends Thread {
public SimpleThread(String str) {
super(str);
}
public void run() {
for (int i = 0; i < 10; i++) {
System.out.println(i + " " + getName());
try {
// Add your customized code here to update the contents in the database.
sleep((int)(Math.random() * 1000));
} catch (InterruptedException e) {}
}
System.out.println("DONE! " + getName());
}
}
有人建议从java.util.concurrent包Java 5的扩展包含更好解决这个问题。 – dendini 2013-07-24 09:15:01
的替代方法创建一个线程自己是使用ExcecutorService,其中 Executors.newScheduledThreadPool(1)
创建大小的thred池1 和scheduleAtFixedRate
有签名:scheduleAtFixedRate(Runnable command, long initialDelay, long period, TimeUnit unit);
public class ScheduledDBPoll
{
public static void main(String[] args)
{
ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
ScheduledFuture<?> sf = scheduler.scheduleAtFixedRate(
new Runnable() {
public void run() {
pollDB();
}
},
1, 60,TimeUnit.SECONDS);
}
}
“我是不是应该启动一个线程&把它在休眠模式下1分钟” 即使你想你想要去与传统的螺纹(不想使用执行Fremework)不要使用休眠等待目的,因为它不会释放锁定和阻止操作。在这里使用等待(超时)。
错误的做法 -
public synchronized void doSomething(long time) throws InterruptedException {
// ...
Thread.sleep(time);
}
正确对待
public synchronized void doSomething(long timeout) throws InterruptedException {
// ...
while (<condition does not hold>) {
wait(timeout); // Immediately releases the current monitor
}
}
+1:'newScheduledThreadPool(1)'='newSingleThreadScheduledExecutor()'和'executor.shutdown()'将取消所有活动任务。 – 2011-12-20 08:20:02
使用Executor的好处是您可以添加许多共享相同线程的各种间隔的重复任务。 (和简单的关机) – 2011-12-20 08:21:34
@PeterLawrey:你说得对。我融入了答案。 – dmeister 2011-12-20 10:49:42