java 中的 Executor 与 ExecutorService 及其实现

一)展示他们的整体关系  ExecutorService extends Executor 注意这里的 Executor 是一个接口

二)

    1.public class ThreadPoolExecutor extends AbstractExecutorService 继承了 AbstractExecutorService  抽象类

    2.public abstract class AbstractExecutorService implements ExecutorService 实现了 ExecutorService 接口

public interface Executor {

    /**
     * Executes the given command at some time in the future.  The command
     * may execute in a new thread, in a pooled thread, or in the calling
     * thread, at the discretion of the <tt>Executor</tt> implementation.
     *
     * @param command the runnable task
     * @throws RejectedExecutionException if this task cannot be
     * accepted for execution.
     * @throws NullPointerException if command is null
     */
    void execute(Runnable command);
}

该接口仅有一个

1)java.util.concurrent 包中 Executor查看 jdk  1.7.0_80  为一个接口,该接口中定义了一个无返回值的execute 方法 ,参数类型为Runnable

2)ExecutorService 接口中定义的12个方法中经常使用的方法有三个

    1.Future<?> submit(Runnable task);使用起来很方便只要将新建的线程循环加入变可

    2.void shutdown();

    3.boolean isTerminated();

3)public class Executors 类 在使用 java 原生的线程池中 该类的静态方法提供了创建不同形式的线程池

  public static ExecutorService newFixedThreadPool(int nThreads) {
        return new ThreadPoolExecutor(nThreads, nThreads,
                                      0L, TimeUnit.MILLISECONDS,
                                      new LinkedBlockingQueue<Runnable>());
    }

以newFixedThreadPool 为例(其他方法类似)根据源码可以看出 new 了一个

ThreadPoolExecutor(nThreads, nThreads,  0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>()) 类型的对象

    1.public class ThreadPoolExecutor extends AbstractExecutorService 继承了 AbstractExecutorService  抽象类

    2.public abstract class AbstractExecutorService implements ExecutorService 实现了 ExecutorService 接口

    3 所以在调用的时候写出

ExecutorService executer = Executors.newFixedThreadPool(nThreads);
		for(int i = 0 ;i<10 ;i++) {
			Runnable t = new TestThread();
			executer.submit(t);
		}
		executer.shutdown();//告诉线程池不在提交了,不调用此方法线程池一直等待,不会结束
		//如果不用判断是否结束 到这里便可
		//如果需要判断线程池里的所有线程都要结束才执行后面的代码就要
		while(true) {
			if(executer.isTerminated()) {
				break;
			}
			try {
				Thread.sleep(200l);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}

的时候实际是调用ThreadPoolExecutor 继承来自抽象类 AbstractExecutorService 实现 ExecutorService 中的代码

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值