我们经常使用的java定时器单线程执行,例如:
一个任务每个一秒中执行一次,加入在50秒的任务没有执行完毕,后续任务无法执行
防止这种策略的是:
在内部在开一个线程,做你想做的事:
public class SchedulePool {
private static ScheduledExecutorService schedulePool = Executors.newScheduledThreadPool(8);
/**
* @param args
*/
static int i =0;
public static void main(String[] args) {
schedulePool.scheduleAtFixedRate(new Thread() {
@Override
public void run() {
try {
System.out.println("运行了一次。。。。。。。"+(i++));
int i=0;
new Thread(new Runnable(){ // 内部在开一个线程,就不会因为上一次任务没有结束人等待了,才可以做到并行执行。
public void run(){
while(true){
Thread.yield();
}
}
}).start();
System.out.println("over------------------>>>>>>>>>>>>>>>>>>>>>.");
/*while(true){
Thread.yield();
}*/
/*while(i<=0){
i++;
Thread.sleep(1000*120);
}*/
} catch (Exception e) {
e.printStackTrace();
}
}
}, 1, 2, TimeUnit.SECONDS);
}
}
一个任务每个一秒中执行一次,加入在50秒的任务没有执行完毕,后续任务无法执行
防止这种策略的是:
在内部在开一个线程,做你想做的事:
public class SchedulePool {
private static ScheduledExecutorService schedulePool = Executors.newScheduledThreadPool(8);
/**
* @param args
*/
static int i =0;
public static void main(String[] args) {
schedulePool.scheduleAtFixedRate(new Thread() {
@Override
public void run() {
try {
System.out.println("运行了一次。。。。。。。"+(i++));
int i=0;
new Thread(new Runnable(){ // 内部在开一个线程,就不会因为上一次任务没有结束人等待了,才可以做到并行执行。
public void run(){
while(true){
Thread.yield();
}
}
}).start();
System.out.println("over------------------>>>>>>>>>>>>>>>>>>>>>.");
/*while(true){
Thread.yield();
}*/
/*while(i<=0){
i++;
Thread.sleep(1000*120);
}*/
} catch (Exception e) {
e.printStackTrace();
}
}
}, 1, 2, TimeUnit.SECONDS);
}
}
本文介绍了一种在Java中使用ScheduledExecutorService并发执行定时任务的方法,通过内部开启线程实现任务并行执行,确保任务执行的高效性和稳定性。

20万+

被折叠的 条评论
为什么被折叠?



