使用callable进行延迟运行
public class MyCallableA implements Callable<String> {
@Override
public String call() throws Exception {
String name = Thread.currentThread().getName();
System.out.println(name+" callA start "+ System.currentTimeMillis());
TimeUnit.SECONDS.sleep(1);
System.out.println(name+" callA end "+ System.currentTimeMillis());
return "result callA";
}
}
public class MyCallableB implements Callable<String> {
@Override
public String call() throws Exception {
String name = Thread.currentThread().getName();
System.out.println(name+" callB start "+ System.currentTimeMillis());
System.out.println(name+" callB end "+ System.currentTimeMillis());
return "result callB";
}
}
public static void main(String[] args) {
List<Callable> list = new ArrayList<Callable>();
list.add(new MyCallableA());
list.add(new MyCallableB());
// 创建单一任务执行计划
// ScheduledExecutorService ex = Executors.newSingleThreadScheduledExecutor();
// 创建多任务执行计划
ScheduledExecutorService ex = Executors.newScheduledThreadPool(2);
ScheduledFuture<String> fua = ex.schedule(list.get(0), 4, TimeUnit.SECONDS);
ScheduledFuture<String> fub = ex.schedule(list.get(1), 4, TimeUnit.SECONDS);
System.out.println("main x start "+System.currentTimeMillis());
try {
System.out.println("返回值A "+fua.get());
System.out.println("返回值B "+fub.get());
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ExecutionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("main x end "+System.currentTimeMillis());
}
}
单一任务执行计划 测试结果
main x start 1601866894411
pool-1-thread-1 callA start 1601866898413
pool-1-thread-1 callA end 1601866899414
返回值A result callA
pool-1-thread-1 callB start 1601866899414
pool-1-thread-1 callB end 1601866899414
返回值B result callB
main x end 1601866899415
总的运行时间是延迟时间加上两个任务的运行时间,第二个人任务是在第一个任务执行完后再执行。
创建多任务执行计划 测试结果
main x start 1601866979774
pool-1-thread-1 callA start 1601866983775
pool-1-thread-2 callB start 1601866983775
pool-1-thread-2 callB end 1601866983775
pool-1-thread-1 callA end 1601866984775
返回值A result callA
返回值B result callB
main x end 1601866984775
到达延迟执行时间后两个任务同时运行。
scheduleAtFixedRate 实现周期性执行
scheduleAtFixedRate(Runnable command,
long initialDelay,
long period,
TimeUnit unit);
command 自定义的runnable接口
initialDelay 延迟执行时间
period 周期
unit 时间单位
public class MyRunnableA implements Runnable {
@Override
public void run() {
String name = Thread.currentThread().getName();
System.out.println(name+" callA start "+ System.currentTimeMillis());
try {
TimeUnit.SECONDS.sleep