Java线程与线程池

java线程创建方式

  • 继承thread
  • 实现runable接口
  • 实现callable和future

线程池体系

在这里插入图片描述

在这里插入图片描述

Executor

抽象出定义一个执行无返回值的任务方法

public interface Executor {
    void execute(Runnable command);
}

ExecutorService

抽象出定义了线程池的动作

public interface ExecutorService extends Executor {
    //关闭
    void shutdown();

    List<Runnable> shutdownNow();
    
    boolean isShutdown();
   
    boolean isTerminated();

    boolean awaitTermination(long timeout, TimeUnit unit)  throws InterruptedException;
    //提交任务
    <T> Future<T> submit(Callable<T> task);

    <T> Future<T> submit(Runnable task, T result);

    Future<?> submit(Runnable task);
     //执行所有任务
    <T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks) throws InterruptedException;

    <T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks, long timeout, TimeUnit unit)  throws InterruptedException;
    //执行任一任务
    <T> T invokeAny(Collection<? extends Callable<T>> tasks)  throws InterruptedException, ExecutionException;

    <T> T invokeAny(Collection<? extends Callable<T>> tasks, long timeout, TimeUnit unit)throws InterruptedException, ExecutionException, TimeoutException;
}

AbstractExecutorService

使用模板方法抽象定义了一些线程池常用的方法,都会调用子类实现的execute(ftask)方法。

   public <T> Future<T> submit(Callable<T> task) {
        if (task == null) throw new NullPointerException();
        RunnableFuture<T> ftask = newTaskFor(task);
        execute(ftask);
        return ftask;
    }
##  RunnableFuture<T> ftask = newTaskFor(task);
 protected <T> RunnableFuture<T> newTaskFor(Callable<T> callable) {
        return new FutureTask<T>(callable);
 }

FutureTask继承关系:
在这里插入图片描述
Future接口定义了一些获取结果的包装方法。

public interface Future<V> {

	 boolean cancel(boolean mayInterruptIfRunning);
	 boolean isCancelled();
	 boolean isDone();
	 V get() throws InterruptedException, ExecutionException;
	 V get(long timeout, TimeUnit unit)
	        throws InterruptedException, ExecutionException, TimeoutException;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值