初试java线程池

线程池

提前创建好多个线程,提前放入到线程池中,使用时直接获取,使用完放回池中。可以避免频繁创建销毁、实现重复利用。

好处

  • 提高响应速度
  • 降低资源消耗
  • 便于线程管理
    • corePoolSize:核心池的大小
    • maximunPoolSize:最大线程数
    • keepAliveTime:保持活跃的时间

1.ExecutorService

public interface ExecutorService
extends Executor

一个 Executor,管理终端和方法可以用于跟踪一个或多个异步任务的进展产生 Future提供方法。

一个ExecutorService可以关闭,这将导致它拒绝新的任务。提供关闭ExecutorService两种不同的方法。该方法将允许shutdown()先前提交的任务执行前终止,而shutdownNow()方法防止等待任务开始试图停止当前正在执行的任务。在终止时,一个执行者没有主动执行的任务,没有等待执行的任务,也没有新的任务可以提交。一个未使用的ExecutorService应该关闭允许其资源回收。

方法submit扩展方法的基础Executor.execute(Runnable)创建并返回一个Future可以取消执行和/或等待完成。方法invokeAnyinvokeAll执行体执行的最常用的形式,执行的任务的集合,然后等待至少一个,或者全部完成。(类ExecutorCompletionService可以用来写这些方法。定制的变体)

Executors类提供了这个包提供的执行服务工厂方法。

使用的例子

这里是一张网络服务中的服务请求的线程的线程池。它使用预先配置的 Executors.newFixedThreadPool(int)工厂方法:

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

以下方法关闭 ExecutorService两阶段,通过调用 shutdown拒绝传入的任务,然后调用 shutdownNow,如果有必要,取消任何挥之不去的任务:

 void shutdownAndAwaitTermination(ExecutorService pool) {
   pool.shutdown(); // Disable new tasks from being submitted
   try {
     // Wait a while for existing tasks to terminate
     if (!pool.awaitTermination(60, TimeUnit.SECONDS)) {
       pool.shutdownNow(); // Cancel currently executing tasks
       // Wait a while for tasks to respond to being cancelled
       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();
   }
 }

内存一致性效果:在一个RunnableCallable任务提交之前的一个ExecutorService happen-before任何行动采取行动任务的线程,从而发生过结果将通过Future.get()

2.Executors

public class Executors
extends Object

对于 ExecutorExecutorServiceScheduledExecutorServiceThreadFactory厂和实用方法,并 Callable类定义在这个包。这类支持以下几种方法:

  • 方法创建并返回一个ExecutorService设置常用的配置设置。
  • 方法创建并返回一个ScheduledExecutorService设置常用的配置设置。
  • 方法创建并返回一个“包装”服务,使重构的具体实施方法不。
  • 方法创建并返回一个新创建的线程ThreadFactory设置到一个已知的状态。
  • 方法创建并返回一个Callable出其他封闭状的形式,可用于执行方法需要Callable

3.代码

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class TestPool {
    
    

    public static void main(String[] args) {
    
    
        //1.创建服务
        ExecutorService service = Executors.newFixedThreadPool(10);

        //2.执行服务
        service.execute(new Pools());
        service.execute(new Pools());
        service.execute(new Pools());
        service.execute(new Pools());
        service.execute(new Pools());
        service.execute(new Pools());
        service.execute(new Pools());
        service.execute(new Pools());
        service.execute(new Pools());
        service.execute(new Pools());
//        service.execute(new Pools());多于数目并不会创建,也不会报错
//        service.execute(new Pools());
//        service.execute(new Pools());

        //3.结束服务
        service.shutdown();


    }

}

class Pools implements Runnable{
    
    
    @Override
    public void run() {
    
    
        System.out.println(Thread.currentThread().getName());
    }
}

猜你喜欢

转载自blog.csdn.net/joey_ro/article/details/109963581