使用 Executors 工厂类来创建不同类型的 ExecutorService。


newFixedThreadPool(int n) 可以创建一个固定大小的线程池。


newCachedThreadPool() 则可以创建一个根据需要自动扩展的线程池。


实际案例:


创建一个简单的多线程程序,使用 ExecutorService 执行一批任务,并获取它们的执行结果。


public static void main(String[] args) {

       // 创建一个固定大小为3的线程池

       ExecutorService executor = Executors.newFixedThreadPool(3);


       // 创建一个列表来保存提交的任务

       List<Future<Integer>> futures = new ArrayList<>();


       // 提交10个任务,每个任务返回任务ID乘以2的结果

       for (int i = 1; i <= 10; i++) {

           final int taskId = i;

           // 提交 Callable 任务,并将 Future 对象保存到列表中

           Future<Integer> future = executor.submit(() -> {

               System.out.println("任务 " + taskId + " 开始执行");

               // 模拟任务执行耗时

               Thread.sleep(2000);  

               // 返回任务的结果

               return taskId * 2;  

           });

           // 将 Future 对象添加到列表中

           futures.add(future);  

       }


       // 等待所有任务完成,并打印各任务的执行结果

       for (Future<Integer> future : futures) {

           try {

               // 获取任务执行结果,可能会阻塞直到任务完成

               Integer result = future.get();  

               System.out.println("任务结果: " + result);

           } catch (InterruptedException | ExecutionException e) {

               e.printStackTrace();

           }

       }


       // 关闭线程池

       executor.shutdown();

   }


// 输出结果

任务 1 开始执行

任务 2 开始执行

任务 3 开始执行

任务结果: 2

任务结果: 4

任务 4 开始执行

任务结果: 6

任务 5 开始执行

任务结果: 8

任务 6 开始执行

任务结果: 10

任务 7 开始执行

任务结果: 12

任务 8 开始执行

任务结果: 14

任务 9 开始执行

任务结果: 16

任务 10 开始执行

任务结果: 18

任务结果: 20

    public JSONObject postHttpReq(String json, String url) {
        // 获取http客户端
        CloseableHttpClient httpClient = HttpClientManager.getCloseableHttpClient();
        // 设置超时时间
        RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(5000).setSocketTimeout(20000).setConnectionRequestTimeout(5000).build();
        // 封装请求参数
        byte[] b = json.getBytes();
        HttpEntity httpEntity = new ByteArrayEntity(b);
        String responseMsg = "";
        int statusCode = 0;
        CloseableHttpResponse response = null;
        try {
            // 创建httpPost请求
            HttpPost httpPost = new HttpPost(url);
            httpPost.setConfig(requestConfig);
            httpPost.setEntity(httpEntity);
            httpPost.setHeader("Content-Type", "application/json;charset=GBK");
            // 执行请求
            response = httpClient.execute(httpPost);
            // 获取请求结果
            statusCode = response.getStatusLine().getStatusCode();
            responseMsg = EntityUtils.toString(response.getEntity());
        } catch (IOException e1) {
            e1.printStackTrace();
        } finally {
            try {
                // 关闭当前请求
                response.close();
            } catch (IOException e2) {
                e2.printStackTrace();
            }
        }
        // 解析请求结果
        if (statusCode != 200) {
            // 输出错误信息
        } else {
            return new JSONObject(responseMsg);
        }
    }