JAVA并发编程--ExecutorService与CompletionService

Future接口介绍

boolean cancel (boolean mayInterruptIfRunning) 取消任务的执行。参数指定是否立即中断任务执行,或者等等任务结束
boolean isCancelled () 任务是否已经取消,任务正常完成前将其取消,则返回 true
boolean isDone () 任务是否已经完成。需要注意的是如果任务正常终止、异常或取消,都将返回true
V get () throws InterruptedException, ExecutionException  等待任务执行结束,然后获得V类型的结果。InterruptedException 线程被中断异常, ExecutionException任务执行异常,如果任务被取消,还会抛出CancellationException
V get (long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException 同上面的get功能一样,多了设置超时时间。参数timeout指定超时时间,uint指定时间的单位,在枚举类TimeUnit中有相关的定义。如果计 算超时,将抛出TimeoutException

ExecutorService多线程执行

ExecutorService executor = Executors.newSingleThreadExecutor();  
FutureTask<String> future =  
       new FutureTask<String>(new Callable<String>() {//使用Callable接口作为构造参数  
         public String call() {  
           //真正的任务在这里执行,这里的返回值类型为String,可以为任意类型  
       }});  
executor.execute(future);  
//在这里可以做别的任何事情  
try {  
    result = future.get(5000, TimeUnit.MILLISECONDS); //取得结果,同时设置超时执行时间为5秒。同样可以用future.get(),不设置执行超时时间取得结果  
} catch (InterruptedException e) {  
    futureTask.cancel(true);  
} catch (ExecutionException e) {  
    futureTask.cancel(true);  
} catch (TimeoutException e) {  
    futureTask.cancel(true);  
} finally {  
    executor.shutdown();  
}  

Runnable:线程执行,没有返回结果
Callable:可以返回线程执行结果

CompletionService

public class Test {
    public static void main(String[] args) throws InterruptedException, ExecutionException {
        ExecutorService executor = Executors.newCachedThreadPool();
        CompletionService<Integer> comp = new ExecutorCompletionService<>(executor);
        for(int i = 0; i<5; i++) {
            comp.submit(new Task());
        }
        executor.shutdown();
        int count = 0, index = 1;
        while(count<5) {
            Future<Integer> f = comp.poll();
            if(f == null) {
                System.out.println(index + " 没发现有完成的任务");
            }else {
                System.out.println(index + "产生了一个随机数: " + f.get());
                count++;
            }
            index++;
            TimeUnit.MILLISECONDS.sleep(500);
        }
    }
}

class Task implements Callable<Integer> {

    @Override
    public Integer call() throws Exception {
        Random rand = new Random();
        TimeUnit.SECONDS.sleep(rand.nextInt(7));
        return rand.nextInt();
    }

}

实现了CompletionService接口,它使用在构造函数中提供的Executor来执行任务的。它会把完成了的任务放一个队列中, 外部可以通过take(),poll(),poll(long timeout,TimeUnit unit)来取得。该类非常轻便,适合于在执行几组任务时临时使用。

public Future<V> take()
               throws InterruptedException
    从接口 CompletionService 复制的描述
    获取并移除表示下一个已完成任务的 Future,如果目前不存在这样的任务,则等待。
    指定者:
        接口 CompletionService<V> 中的 take
    返回:
        表示下一个已完成任务的 Future 
    抛出:
        InterruptedException - 如果在等待时被中断
public Future<V> poll()
    从接口 CompletionService 复制的描述
    获取并移除表示下一个已完成任务的 Future,如果不存在这样的任务,则返回 null。
    指定者:
        接口 CompletionService<V> 中的 poll
    返回:
        表示下一个已完成任务的 Future;如果不存在这样的任务,则返回 null
public Future<V> poll(long timeout,
                      TimeUnit unit)
               throws InterruptedException
    从接口 CompletionService 复制的描述
    获取并移除表示下一个已完成任务的 Future,如果目前不存在这样的任务,则将等待指定的时间(如果有必要)。
    指定者:
        接口 CompletionService<V> 中的 poll
    参数:
        timeout - 放弃之前需要等待的时间长度,以 unit 为时间单位
        unit - 确定如何解释 timeout 参数的 TimeUnit 
    返回:
        表示下一个已完成任务的 Future;如果等待了指定时间仍然不存在这样的任务,则返回 null 
    抛出:
        InterruptedException - 如果在等待时被中断
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值