java 线程池配置

博客围绕多线程展开,但具体内容缺失。多线程是信息技术领域重要概念,可提高程序执行效率等。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

package website.thread;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;


/**
 * 线程池模拟
 *
 * @author lizixian
 * @date 2021/6/3 10:30
 */
public class MyThreadPool {

    private static ThreadPoolExecutor executor;

    static {
        executor = new ThreadPoolExecutor(4, 8,
                100, TimeUnit.MILLISECONDS, new ArrayBlockingQueue<>(2), new MyRejectPolicy());
    }

    // jdk 给出的几种拒绝handler
    // 线程池对拒绝任务(无线程可用)的处理策略
    // executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());    // 用调用者所在的线程来执行任务(主线线程去执行当前任务,等待线程池有空闲继续执行)
    // executor.setRejectedExecutionHandler(new ThreadPoolExecutor.AbortPolicy());         // 直接抛出异常,这是默认策略
    // executor.setRejectedExecutionHandler(new ThreadPoolExecutor.DiscardOldestPolicy()); // 丢弃阻塞队列中靠最前的任务,并执行当前任务
    // executor.setRejectedExecutionHandler(new ThreadPoolExecutor.DiscardPolicy());       // 直接丢弃任务


    /**
     * 自定义拒绝handler
     *
     * @author lizixian
     * @date 2021/6/3 10:29
     */
    static class MyRejectPolicy implements RejectedExecutionHandler {
        public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
            if (r instanceof MyThread) {
                MyThread myThread = (MyThread) r;
                System.out.println("线程池拒绝了:" + myThread.getThreadName());
            }
        }
    }


    /**
     * 自定义线程类
     *
     * @author lizixian
     * @date 2021/6/3 10:28
     */
    static class MyThread implements Runnable {

        private String threadName;

        MyThread(String threadName) {
            this.threadName = threadName;
        }

        public String getThreadName() {
            return threadName;
        }

        public void setThreadName(String threadName) {
            this.threadName = threadName;
        }

        @Override
        public void run() {
            Thread.currentThread().setName(threadName);

            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            System.out.println("当前线程:" + Thread.currentThread().getName());
        }
    }

    public static void main(String[] args) {

        for (int i = 0; i < 12; i++) {
            executor.execute(new MyThread("我是第" + i + "个线程"));
        }
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值