当需要对线程进行时间上的调度时,Java提供了两种方案:
- Timer + TimerTask
- ScheduledExecutorService
区别:
Timer有很大的局限性,内部只有一个工作线程,如有个线程需要调度时,只能串行执行。
ScheduledExecutorService提供线程池,可以并行的进行任务调度。
Timer案例:
package thread;
import java.util.Timer;
import java.util.TimerTask;
public class TimerTest {
public static void main(String[] args) {
Timer timer = new Timer();
TimerTask task = new TimerTask() {
@Override
public void run() {
System.out.println("执行");
try {
Thread.sleep(4000l);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
TimerTask task2 = new TimerTask() {
@Override
public void run() {
System.out.println("执行2");
}
};
timer.schedule(task,1000);
timer.schedule(task2,1000);
}
}
ScheduledExecutorService使用代码:
public class ScheduledThreadPoolExecutorTest {
public static void main(String[] args) {
ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(2);
scheduledExecutorService.schedule(new Runnable() {
@Override
public void run() {
System.out.println("执行1。。。。");
}
},1, TimeUnit.SECONDS);
scheduledExecutorService.schedule(new Runnable() {
@Override
public void run() {
System.out.println("执行2。。。。");
}
},1, TimeUnit.SECONDS);
}
}