import java.util.Date;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
public class ScheduledThreadPoolExecutorExample {
private static class Task implements Runnable {
private String name;
public Task(String name) {
this.name = name;
}
@Override
public void run() {
try {
System.out.println("execute:"+name);
} catch (Exception e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
ScheduledThreadPoolExecutor scheduledThreadPoolExecutor = new ScheduledThreadPoolExecutor(2);
Task task1 = new Task("Task1");
Task task2 = new Task("Task2");
System.out.println("The time is : " + new Date());
scheduledThreadPoolExecutor.schedule(task1,5, TimeUnit.SECONDS);
scheduledThreadPoolExecutor.schedule(task2,10,TimeUnit.SECONDS);
try{
System.out.println("wait ...");
scheduledThreadPoolExecutor.awaitTermination(20,TimeUnit.SECONDS); //这会阻塞
System.out.println("end wait ...");
}catch (Exception e){
e.printStackTrace();
}
}
}
ScheduledThreadPoolExecutor
最新推荐文章于 2024-09-07 18:58:16 发布