Executor接口与Executors创建简单线程池

Executor接口介绍

Executor接口仅仅是定义了一种规范,没有实现任何功能。
API接口源码

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 {@code Executor} 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);
}

Executor接口结构
Executor完整的接口类继承图

使用Executors工厂类创建线程池

  1. 创建无界线程池 ,可进行线程自动回收,理论上线程个数为Integer.MAX_VALUE。
    ExecutorService newCachedThreadPool();
    ExecutorService newCachedThreadPool(ThreadFactory threadFactory);
 	 public static ExecutorService newCachedThreadPool() {
        return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
                                      60L, TimeUnit.SECONDS,
                                      new SynchronousQueue<Runnable>());
    }
    
     public static ExecutorService newCachedThreadPool(ThreadFactory threadFactory) {
        return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
                                      60L, TimeUnit.SECONDS,
                                      new SynchronousQueue<Runnable>(),
                                      threadFactory);
    }
  1. 创建有界线程池,指定线程池中线程最大数量。
    ExecutorService newFixedThreadPool(int nThreads);
    ExecutorService newFixedThreadPool(int nThreads, ThreadFactory threadFactory);
	 public static ExecutorService newFixedThreadPool(int nThreads) {
        return new ThreadPoolExecutor(nThreads, nThreads,
                                      0L, TimeUnit.MILLISECONDS,
                                      new LinkedBlockingQueue<Runnable>());
    }

	  public static ExecutorService newFixedThreadPool(int nThreads, ThreadFactory threadFactory) {
        return new ThreadPoolExecutor(nThreads, nThreads,
                                      0L, TimeUnit.MILLISECONDS,
                                      new LinkedBlockingQueue<Runnable>(),
                                      threadFactory);
    }
  1. 创建单一线程池,可以实现以队列的方式执行任务。
    ExecutorService newSingleThreadExecutor();
    ExecutorService newSingleThreadExecutor(ThreadFactory threadFactory);
	public static ExecutorService newSingleThreadExecutor() {
        return new FinalizableDelegatedExecutorService
            (new ThreadPoolExecutor(1, 1,
                                    0L, TimeUnit.MILLISECONDS,
                                    new LinkedBlockingQueue<Runnable>()));
    }

	  public static ExecutorService newSingleThreadExecutor(ThreadFactory threadFactory) {
        return new FinalizableDelegatedExecutorService
            (new ThreadPoolExecutor(1, 1,
                                    0L, TimeUnit.MILLISECONDS,
                                    new LinkedBlockingQueue<Runnable>(),
                                    threadFactory));
    }

使用newFixedThreadPool的例子:
自定义的线程工厂

	public class MyThreadFactory implements ThreadFactory{

	@Override
	public Thread newThread(Runnable r) {
		Thread thread = new Thread(r);
		thread.setName("定制线程池大小的自定义线程工厂 ");
		return thread;
	}

}

创建固定大小的有界线程池

import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

public class MyThreadPoolExecutor {
	public static void main(String[] args) {
		MyThreadFactory myThreadFactory = new MyThreadFactory();
		Executor executor = Executors.newFixedThreadPool(2,myThreadFactory);
		for(int i = 0; i<5;i++) {
			executor.execute(()->{
				System.out.println(Thread.currentThread().getName()+" begin "+System.currentTimeMillis());
				try {
					TimeUnit.MILLISECONDS.sleep(1000);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				System.out.println(Thread.currentThread().getName()+" end "+System.currentTimeMillis());
			});
		}
	}
}

运行结果:
定制线程池大小的自定义线程工厂 begin 1596336545519
定制线程池大小的自定义线程工厂 begin 1596336545519
定制线程池大小的自定义线程工厂 end 1596336546519
定制线程池大小的自定义线程工厂 end 1596336546519
定制线程池大小的自定义线程工厂 begin 1596336546519
定制线程池大小的自定义线程工厂 begin 1596336546519
定制线程池大小的自定义线程工厂 end 1596336547520
定制线程池大小的自定义线程工厂 end 1596336547520
定制线程池大小的自定义线程工厂 begin 1596336547520
定制线程池大小的自定义线程工厂 end 1596336548521

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值