[英]Worker Thread in 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的一个好处是,您可以添加许多不同时间间隔的重复任务,这些任务共享相同的线程池,这是一个简单但受控制的关闭。
自己创建线程的另一种方法是使用ExcecutorService,其中Executors.newScheduledThreadPool( 1 )
创建一个大小为1的thred池, 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)也不要将SLEEP用于等待目的,因为它不会释放锁定和它是一个阻塞操作。 请在这里等待(超时)。
错误的做法 -
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
}
}
你的方法很好。你可以继续你的方法。
此示例将帮助您完成任务:
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());
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.