java使用自定义线程池跑多线程,Future 不同的线程返回不同的数据,已经多线程的本地线程变量使用

使用线程池跑多线程

//创建子线程可见的本机线程变量
InheritableThreadLocal inheritableThreadLocal = new InheritableThreadLocal<>();
//创建子线程不可见的本机线程变量
ThreadLocal threadLocal = new ThreadLocal<>();

InheritableThreadLocal可让子线程获取主线程数据

四种线程池创建的方式
newCachedThreadPool
创建一个可缓存线程池,如果线程池长度超过处理需要,可灵活回收空闲线程,若无可回收,则新建线程。

newFixedThreadPool
创建一个定长线程池,可控制线程最大并发数,超出的线程会在队列中等待。

newScheduledThreadPool
创建一个定长线程池,支持定时及周期性任务执行。

newSingleThreadExecutor
创建一个单线程化的线程池执行任务。

/*
 * Copyright 2019 Wicrenet, Inc. All rights reserved.
 */
package com.xy;

import java.util.ArrayList;
import java.util.concurrent.*;

/**
 * 【】
 *
 * @author YJX
 * Created on 2019/10/12 10:53
 */

public class ThreadPoolExecutor {

    //使用 FixedThreadPool线程池
    private static final ExecutorService threadPool = Executors.newFixedThreadPool(10000, (r) -> {
        Thread t = new Thread(r);
        t.setDaemon(true);
        return t;
    });

    //创建子线程可见的本机线程变量
    private final static InheritableThreadLocal<String> inheritableThreadLocal = new InheritableThreadLocal<>();
    //创建子线程不可见的本机线程变量
    private final static ThreadLocal<String>            threadLocal            = new ThreadLocal<>();

    /**
     * 使用线程池获取多个线程的返回数据
     */
    public static void main(String[] argv) {
        long l = System.currentTimeMillis();
        //设置子线程可见的线程本地变量
        inheritableThreadLocal.set("yjx-inheritableThreadLocal-子线程可见");
        //设置线程本地变量
        threadLocal.set("yjx-threadLocal-子线程不可见");
        /*可用线程数量的固定线程池*/
        ExecutorService executorService = threadPool;
        ArrayList<Object> list = new ArrayList<>();
        //向线程池中添加线程
        Future thread1 = executorService.submit(new ThreadRV1());
        Future thread2 = executorService.submit(new ThreadRV2());
        Future thread3 = executorService.submit(new ThreadRV3());
        //...可以加N个线程任务

        executorService.shutdown();//一定要调用这个方法,不然executorService.isTerminated()永远不为true
        while (true) {//等待所有任务都结束了继续执行
            try {
                if (executorService.isTerminated()) {
                    System.out.println("所有的子线程都结束了!");
                    break;
                }
                Thread.sleep(100);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        try {
            list.add(thread1.get());
            list.add(thread2.get());
            list.add(thread3.get());
            System.out.println("所有线程共耗时:" + (System.currentTimeMillis() - l));
            System.out.println("list = " + list);

        } catch (InterruptedException | ExecutionException e) {
            e.printStackTrace();
        }
    }

    public static class ThreadRV1 implements Callable {
        @Override
        public String call() throws Exception {
            long l = System.currentTimeMillis();

            String s = inheritableThreadLocal.get();
            System.out.println("t1s = " + s);
            String s1 = threadLocal.get();
            System.out.println("t1s1 = " + s1);

            System.out.println("线程1开始");
            TimeUnit.SECONDS.sleep(5);
            System.out.println("线程1结束-耗时" + (System.currentTimeMillis() - l));
            return "t1" + s;
        }
    }



    public static class ThreadRV2 implements Callable {
        @Override
        public String call() throws Exception {
            long l = System.currentTimeMillis();
            String s = inheritableThreadLocal.get();
            System.out.println("t1s = " + s);
            String s1 = threadLocal.get();
            System.out.println("t1s1 = " + s1);

            System.out.println("线程2开始");
            TimeUnit.SECONDS.sleep(5);
            System.out.println("线程2结束-耗时" + (System.currentTimeMillis() - l));
            return "t2" + s1;
        }
    }

    //返回Integer类型
    public static class ThreadRV3 implements Callable {
        @Override
        public Integer call() throws Exception {
            long l = System.currentTimeMillis();

            String s = inheritableThreadLocal.get();
            System.out.println("t1s = " + s);
            String s1 = threadLocal.get();
            System.out.println("t1s1 = " + s1);

            System.out.println("线程3开始");
            TimeUnit.SECONDS.sleep(5);
            System.out.println("线程3结束-耗时" + (System.currentTimeMillis() - l));
            return 1;
        }
    }
}


例子2

package com.xy.pay.main.config;

import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.Executor;

/**
 * 线程池 配置
 *
 * @author YJX
 * @date 2019/10/12 15:17
 */
@Configuration
@EnableAsync
public class ExecutorConfig {
    //@Autowired
    //private TraceableThreadFactory traceableThreadFactory;


    /**
     * 默认的线程池
     *
     * @return
     */
    @Bean
    @Primary
    @Qualifier("defaultExecutor")
    public Executor defaultExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(5);/*核心线程数*/
        executor.setMaxPoolSize(10);/*最大线程数*/
        executor.setQueueCapacity(10000);/*队列大小*/
        executor.setKeepAliveSeconds(60);/* 某线程空闲超过1分钟,就回收该线程*/
        //executor.setAllowCoreThreadTimeOut(true);   // KeepAliveSeconds 设置也作用于【核心线程数】
        executor.setThreadNamePrefix("defaultExecutor-");
        //executor.setThreadFactory(traceableThreadFactory);
        executor.setAwaitTerminationSeconds(5);
        executor.setRejectedExecutionHandler(null);
        executor.setWaitForTasksToCompleteOnShutdown(true);
        executor.initialize();
        return executor;
    }

    /**
     * 对账的线程池
     *
     * @return
     */
    @Bean
    @Qualifier("executor")
    public Executor reconciliationExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(3);/*核心线程数*/
        executor.setMaxPoolSize(3);/*最大线程数*/
        executor.setQueueCapacity(10000);/*队列大小*/
        executor.setKeepAliveSeconds(60 * 3);/* 某线程空闲超过3分钟,就回收该线程*/
        executor.setAllowCoreThreadTimeOut(true);   // KeepAliveSeconds 设置也作用于【核心线程数】
        executor.setThreadNamePrefix("executor-");
        //executor.setThreadFactory(traceableThreadFactory);
        executor.setRejectedExecutionHandler(null);
        executor.setWaitForTasksToCompleteOnShutdown(true);
        executor.setAwaitTerminationSeconds(5);
        executor.initialize();
        return executor;
    }

}
    
    @Autowired
    @Qualifier("executor")
    private Executor executor;

    /**
     * @return
     */
    @GetMapping("thread")
    public void store() {

        System.out.println("例子1");
        long startTime = System.currentTimeMillis();
        ThreadPoolTaskExecutor executor1 = (ThreadPoolTaskExecutor) this.executor;
        Future<String> submit1 = executor1.submit(this::a1);
        Future<String> submit2 = executor1.submit(this::a2);

        ArrayList<Object> list1 = new ArrayList<>();
        try {
            String s1 = submit1.get();
            String s2 = submit2.get();
            list1.add(s1);
            list1.add(s2);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        long endTime1 = System.currentTimeMillis();
        System.out.println("list1 = " + list1);
        System.out.println("例子1总耗时 = " + (endTime1 - startTime));

    }

   public String a1(){
       try {
           TimeUnit.SECONDS.sleep(3);
           System.out.println("a1完成");
       } catch (InterruptedException e) {
           e.printStackTrace();
       }
       return "yyyl";
    }

    public String a2(){
        try {
            TimeUnit.SECONDS.sleep(4);
            System.out.println("a2完成");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return "yyy2";
    }

你可能感兴趣的:(Spring,java,Thread多线程)