General multithreaded creation

for(int i= 1; i<=2; i++){ new Thread(new Runnable() { @Override public void run() { for(int i= 0; i<10; i++){ System.out.println(Thread.currentThread().getName()); } } }).start(); }Copy the code

Thread pool definition used in conjunction with Lambada

public class ThreadPoolUtils {
    private static final ExecutorService threadPool;

    static {
        int corePoolSize = 30;
        int maxPoolSize = 40;
        long keepAliveTime = 5;
        TimeUnit keepAliveTimeUnit = TimeUnit.MINUTES;
        int queSize = 100_000;
        ThreadFactory threadFactory = new ThreadFactoryBuilder()
                .setNameFormat("ThreadPoolUtils")
                .build();

        threadPool = new ThreadPoolExecutor(corePoolSize, maxPoolSize,
                keepAliveTime, keepAliveTimeUnit, new ArrayBlockingQueue<>(queSize)
                , threadFactory);
    }


    /**
     * 获取线程池
     * @return 线程池
     */
    public static ExecutorService getThreadPool() {
        return threadPool;
    }
Copy the code
ExecutorService executor = ThreadPoolUtils.getThreadPool(); for(int i= 1; i<=2; i++){ int finalI = i; executor.submit(()->{ for(int i= 0; i<10; i++){ System.out.println(Thread.currentThread().getName()); }}}); } executor.shutdown();Copy the code