线程池

线程池的特点是:可重复利用线程,减少资源消耗。提高效率,对于需要单个线程执行的程序来说若是没有线程则会每次需要新创建线程去跑,跑完线程就自动销毁了。

1.自定义线程工厂。

package test;

import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 
 * @describe 自定义线程池,当创建线程时可指定线程的一些配置。也可用jdk或其他第三方提供好的。
 *
 * @author li.yanlong@icjhd.com
 *
 * @date 2022-4-7 11:18:13
 */
public class CustomThreadFactory implements ThreadFactory {

    private final AtomicInteger i = new AtomicInteger(1);

    @Override
    public Thread newThread(Runnable r) {
         // 创建线程,并指定任务
        Thread thread = new Thread(r);
        // 设置线程名称
        thread.setName("线程" + i.getAndIncrement() + "号");
        // 返回线程
        return thread;
    }

}

 

2.生成线程任务类。

package test;

public class Task implements Runnable {

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

 

3.测试。

package test;

import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class Test {

    public static void main(String[] args) {
        // 创建任务
        Task task1 = new Task();
        Task task2 = new Task();
        Task task3 = new Task();
        Task task4 = new Task();
        Task task5 = new Task();
        Task task6 = new Task();
        // 创建线程池:此线程池是原生线程池,推荐使用。
        // 参数:核心线程数,最大线程数,空闲线程时间,空闲时间单位,线程队列,线程工厂,线程阻塞时的处理(这里选的是抛出异常)
        ThreadPoolExecutor threadPool = new ThreadPoolExecutor(4, 5, 10L, TimeUnit.SECONDS, new LinkedBlockingQueue<>(),
                new CustomThreadFactory(), new ThreadPoolExecutor.AbortPolicy());
        // 提交任务
        threadPool.execute(task1);
        threadPool.execute(task2);
        threadPool.execute(task3);
        threadPool.execute(task4);
        threadPool.execute(task5);
        threadPool.execute(task6);
        // 关闭线程池
        threadPool.shutdown();
        /*
         * 输出:线程1号 线程4号 线程2号 线程3号 线程4号 线程1号
         */
    }
}

 

posted @ 2022-04-07 11:45  ~~mr.li~~  阅读(39)  评论(0)    收藏  举报