Timer与ScheduledExecutorService定时器的比较及其简单事例

来源:互联网 发布:淘宝退款优惠券退吗 编辑:程序博客网 时间:2024/05/16 07:30
import java.util.concurrent.ExecutionException;import java.util.concurrent.Executors;import java.util.concurrent.ScheduledExecutorService;import java.util.concurrent.ScheduledFuture;import java.util.concurrent.TimeUnit;/** * JDK 1.5之后有了ScheduledExecutorService,不建议你再使用java.util.Timer, * 因为它无论功能性能都不如ScheduledExecutorService。 */public class ScheduledExecutorServiceTest {public static void main(String[] args) throws InterruptedException, ExecutionException {ScheduledExecutorService schedu = Executors.newScheduledThreadPool(1);Runnable command = new Runnable(){@Overridepublic void run() {System.out.println("run 执行.............");}};//功能:创建并执行在给定延迟后启用的一次性操作。对command任务暂停十秒后执行ScheduledFuture future = schedu.schedule(command, 10, TimeUnit.SECONDS);//返回:表示挂起任务完成的 Future,并且其 get() 方法在完成后将返回 null。//System.out.println(future.get());//试图取消对此任务的执行//future.cancel(true);//启动一次顺序关闭,执行以前提交的任务,但不接受新任务。schedu.shutdown();//一个显示等待时间的功能int count=0;while(true){if(!future.isDone()){Thread.sleep(1000);System.out.println(++count+"秒");}else{break;}}}/** * 运行结果:    1秒2秒3秒4秒5秒6秒7秒8秒9秒run 执行.............10秒 */}


import java.util.Timer;import java.util.TimerTask;public class TimerTest {public static void main(String[] args) throws InterruptedException {//因为在内部类中要使用final,但是又要改变值,故只能使用引用型的变量final Boolean[] bs = new Boolean[]{false};Timer timer = new Timer();//TimerTask实现了Runnable接口TimerTask task = new TimerTask(){@Overridepublic void run() {System.out.println("run 执行.............");bs[0] = true;}};//delay - 执行任务前的延迟时间,单位是毫秒。timer.schedule(task, 1000*10);//暂停后十秒执行int count = 0;while(true){//Timer没有获得执行是否完成的方法,future.isDone()if( !bs[0] ){Thread.sleep(1000); System.out.println(++count+"秒");}else{timer.cancel();//强制取消任务,不会等该任务结束后取消break;}}}/** * 执行结果:    1秒2秒3秒4秒5秒6秒7秒8秒9秒run 执行.............10秒 */}


原创粉丝点击