java 线程池

一、先看一个例子:Executor mExecutor=Executors.newSingleThreadExecutor();

        这个方法是创建一个只有一条线程的线程池。可以使用的场景是在下载文件时,我们如果要求一个下载完再下载下一个的情况下,这个时候文件的下载任务(Runable)是多个的,可以共用同一条线程,在节省资源的同时还方便管理,而不是每个任务都重新开一个线程(会消耗性能)。

      Executors 这个类是一个工厂类,提供了不同线程管理策略的线程池实现类的初始化方法。

 

二、接口: Executor    一个提供了执行任务方法的接口类

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);
}

 

三、直接使用Thread 和Executor 的对比

       使用Thread,无法很方便重复利用已创建的Thread ,也无法很好的管理任务(runnable)

new Thread(new(RunnableTask1())).start():

new Thread(new(RunnableTask2())).start():

      使用Executor:可以通过一些策略来限制线程数,任务的调度。如果有100个任务,不会说马上创建100个线程去执行,(cpu应该扛不住)

 Executor executor = anExecutor;
 executor.execute(new RunnableTask1());
 executor.execute(new RunnableTask2());



四、ExecutorService   提供管理终止和的方法的执行程序方法,可以产生一个未来的跟踪进展一个或多个异步任务。

public interface ExecutorService extends Executor {

    //shutdown和shutdownNow都是即时执行终止任务
    void shutdown();

   
    List<Runnable> shutdownNow();

  
    boolean isShutdown();

   
    boolean isTerminated();
   

 

五、官方例子

下面是Executor的实现例子:(源码里抄出来的)

class SerialExecutor implements Executor {
*   final Queue<Runnable> tasks = new ArrayDeque<>();//任务队列(多个任务)顺序执行
*   final Executor executor;
*   Runnable active;
*
*   SerialExecutor(Executor executor) {
*     this.executor = executor;
*   }
*
*   public synchronized void execute(final Runnable r) {
*     tasks.add(new Runnable() {
*       public void run() {
*         try {
*           r.run();
*         } finally {
*           scheduleNext();
*         }
*       }
*     });
*     if (active == null) {
*       scheduleNext();
*     }
*   }
*
*   protected synchronized void scheduleNext() {
*     if ((active = tasks.poll()) != null) {
*       executor.execute(active);
*     }
*   }
* }}

下面是 ExecutorService 的使用例子(源码里抄出来的):

* class NetworkService implements Runnable {
*   private final ServerSocket serverSocket;
*   private final ExecutorService pool;
*
*   public NetworkService(int port, int poolSize)
*       throws IOException {
*     serverSocket = new ServerSocket(port);
*     pool = Executors.newFixedThreadPool(poolSize);
*   }
*
*   public void run() { // run the service
*     try {
*       for (;;) {
*         pool.execute(new Handler(serverSocket.accept()));
*       }
*     } catch (IOException ex) {
*       pool.shutdown();
*     }
*   }
* }
*
* class Handler implements Runnable {
*   private final Socket socket;
*   Handler(Socket socket) { this.socket = socket; }
*   public void run() {
*     // read and service request on socket
*   }
* }}</pre>
*
* The following method shuts down an {@code ExecutorService} in two phases,
* first by calling {@code shutdown} to reject incoming tasks, and then
* calling {@code shutdownNow}, if necessary, to cancel any lingering tasks:
*
*  <pre> {@code
* void shutdownAndAwaitTermination(ExecutorService pool) {
*   pool.shutdown(); // 禁止新的任务被提交
*   try {
*     // 等待一段时间终止现有的任务
*     if (!pool.awaitTermination(60, TimeUnit.SECONDS)) {
*       pool.shutdownNow(); // 取消当前执行的任务
*       // 一段等待任务应对被取消
*       if (!pool.awaitTermination(60, TimeUnit.SECONDS))
*           System.err.println("Pool did not terminate");
*     }
*   } catch (InterruptedException ie) {
*     // (Re-)Cancel if current thread also interrupted
*     pool.shutdownNow();
*     // Preserve interrupt status
*     Thread.currentThread().interrupt();
*   }
* }}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值