Adi*_*Adi 25 java multithreading servletcontextlistener
我已经在ServletContextListener中调用了一个方法作为线程..现在根据我的需要,我必须将线程延迟1分钟,然后开始执行线程中调用的方法,但我无法做到这一点,因为我是非常新的...
这是我的代码......
public class Startup implements ServletContextListener {
@Override
public void contextDestroyed(ServletContextEvent sce) {
}
public void contextInitialized(ServletContextEvent sce) {
// Do your startup work here
System.out.println("Started....");
//captureCDRProcess();
new Thread(new Runnable() {
@Override
public void run() {
captureCDRProcess();
}
}).start();
}
Run Code Online (Sandbox Code Playgroud)
请帮帮我..先谢谢..
Two*_*The 47
要正确执行此操作,您需要使用ScheduledThreadPoolExecutor并使用如下函数计划:
final ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(NUM_THREADS);
executor.schedule(new Runnable() {
@Override
public void run() {
captureCDRProcess();
}
}, 1, TimeUnit.MINUTES);
Run Code Online (Sandbox Code Playgroud)
Thread.sleep 不是要走的路,因为它不能保证它在一分钟后醒来.根据操作系统和后台任务,它可能是60秒,62秒或3小时,而上面的调度程序实际上使用正确的操作系统实现进行调度,因此更加准确.
此外,该调度程序还允许其他几种灵活的方式来安排固定速率或固定延迟等任务.
编辑:使用新的Java8 Lamda语法的相同解决方案:
final ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(NUM_THREADS);
executor.schedule(() -> captureCDRProcess(), 1, TimeUnit.MINUTES);
Run Code Online (Sandbox Code Playgroud)
Mel*_*des 10
或者您可以使用Timer和TimerTask延迟创建线程:
public void contextInitialized() {
// Do your startup work here
System.out.println("Started....");
Timer timer = new Timer();
TimerTask delayedThreadStartTask = new TimerTask() {
@Override
public void run() {
//captureCDRProcess();
//moved to TimerTask
new Thread(new Runnable() {
@Override
public void run() {
captureCDRProcess();
}
}).start();
}
};
timer.schedule(delayedThreadStartTask, 60 * 1000); //1 minute
}
Run Code Online (Sandbox Code Playgroud)