java-延迟并具有周期性的任务

1、Timer工具管理任务的延迟执行以及周期执行。但是TIMER存在一些缺陷。可以使用ScheduledThreadPollExecutor做为代替品。

2、ScheduledThreadPollExecutor可以提供多个线程来执行延迟、并具周期性任务。

3、如果你构建自己的调度服务,仍然可以使用类库提供的DelayQueue,它是BlockingQueue的实现,为SchedThreadPoolExecutor提供了调度功能。DelayQueue管理着一个包含Delayed对象的容器。

4、

public interface Callable<V>{

   V call() throwsExeception;

}

public interface Future<V>{

  boolean cancel(booleanmayInterruptIfRunning);

  boolean isCanceled();

  boolean isDone();

  V get() throwsInterruptedExeception,ExecutionException,CancellationException;

  V get(long timeout,TimeUnitunit) throwsInterruptedException,ExecutionException,CancelationException,TimeroutException;

5、有很多方法可以创建一个描述任务的Future。ExecutorService中的所有submit方法都返回一个Future,可以将一个Runnable或一个Callable提交给executor,然后得到一个Future,用它来重新获得任务执行的结果,或者取消任务。

6、你可以显式地为给定的Runnable或Callable实例化一个FutureTask。将Runnable或Callable提交到Executor的行为可以建立一个安全发布。

7、浏览网页。一个任务是渲染文本,一个是负责下载图像。

public class FutureRender{

    private final ExecutorService executor=...;

    

    void renderPage(CharSequence source){

       final List<ImageInfo>imageeInfos=scanForImageInfo(source);

       Callable<List<ImageData>>task=

           newCallable<List<IMageData>>(){

               publicList<ImageData> call(){

                   List<ImageData> result=newArrayList<ImageData>();

                    for(ImageInfo imageInfo:imageInfos)

                        result.add(imageInfo.downloadImage());

              } 

           };

     Future<List<ImageData>>future=executor.submit(task);

     renderText(source);

     try{

          List<ImageData>imageData=future.get();

         for (ImageData data:imageData)

              renderImage(data);

     }

    catch (InterruptedException e){

         Thread.currentgThread().interrupt();

         future.cancel(true);

    }

    catch (ExecutionException e)(throwlaunderThrowable(e.getCause));

    }

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值