线程池

线程池

使用线程池的优势:

提高响应速度(减少了创建新线程的时间)

降低资源消耗(重复利用线程池中线程,不需要每次都创建)

便于线程管理

​ corePoolSize: 核心池的大小

​ maximumPoolSize: 最大线程数

​ keepAliveTime: 线程没有任务时最多保持多长时间后会终止

代码

package com.example.multi_thread;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class TestPool {
    public static void main(String[] args) {
        Print print = new Print();
        Print1 print1 = new Print1();
        new Thread(print).start();
        new Thread(print).start();
        new Thread(print).start();
        new Thread(print).start();
        new Thread(print).start();

        System.out.println("=============================================");
        // 线程池
        ExecutorService service = Executors.newFixedThreadPool(10);
        service.execute(print);
        service.submit(print1);
        service.submit(print);
        service.shutdown();

        System.out.println("=============================================");
        // 线程池
        ExecutorService service1 = new ThreadPoolExecutor(5, 10, 1L, TimeUnit.MICROSECONDS, new LinkedBlockingDeque<>());
        service1.submit(print1);
        service1.submit(print);
        service1.shutdown();

    }


}

class Print implements Runnable {

    @Override
    public void run() {
        System.out.println(Thread.currentThread().getName() + "Runnable");
    }
}

class Print1 implements Callable {

    @Override
    public Object call() throws Exception {
        System.out.println(Thread.currentThread().getName() + "callable");
        return null;
    }
}
posted @ 2021-11-15 20:42  Oh,mydream!  阅读(26)  评论(0编辑  收藏  举报