Java—线程池

本文详细介绍了Java线程池的工作原理及使用,通过ThreadPoolExecutor创建线程池,处理Runnable和Callable任务。线程池可以限制并发线程数量,避免资源浪费,当线程池和队列饱和时,采取拒绝策略。示例代码展示了不同参数配置对任务执行的影响。

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

线程池的作用:只启动固定数量的线程,防止并发时产生过多的线程影响性能,线程不够时,其他线程需要进行等待线程池的线程释放才可以使用

一、线程池处理Runnable任务

import java.util.concurrent.*;

public class Test {
    public static void main(String[] args) {
        /**参数说明 ,临时线程是在核心线程忙碌且队列满时启用,线程异常抛出是,核心线程+临时线程+队列满了时,抛出
         * int corePoolSize,核心线程,不会主动关闭
         * int maximumPoolSize, 最大线程,==核心线程+临时线程
         * long keepAliveTime,临时线程为空闲时间
         * TimeUnit unit,临时时间单位
         * BlockingQueue<Runnable> workQueue, 队列个数
         * ThreadFactory threadFactory,工厂方法,默认使用
         * RejectedExecutionHandler handler,线程不足时,新的线程进来抛异常
         */
        ExecutorService pool = new ThreadPoolExecutor(3, 5, 6, TimeUnit.SECONDS,
                                                    new ArrayBlockingQueue<>(5),
                                                    Executors.defaultThreadFactory(),
                                                    new ThreadPoolExecutor.AbortPolicy());
        Myrunnable taget = new Myrunnable();
        pool.execute(taget);
        pool.execute(taget);
        pool.execute(taget);
        pool.execute(taget);
        pool.execute(taget);
        pool.execute(taget);
        pool.execute(taget);
        pool.execute(taget);
        //创建临时线程
        pool.execute(taget);
        pool.execute(taget);
        //已达到最高线程和队列数量,线程抛出
        pool.execute(taget);

    }
}

class Myrunnable implements Runnable{

    @Override
    public void run() {
        for (int i = 0; i < 5; i++) {
            System.out.println(Thread.currentThread().getName() + "输出" + i);
        }
        try {
            Thread.sleep(50000);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

二、线程池处理Callable任务,与Runnable任务类似

package com.ruqi.poolsdemo;

import java.util.concurrent.*;

public class Test {
    public static void main(String[] args) throws Exception{

        ExecutorService pool = new ThreadPoolExecutor(3, 5, 6, TimeUnit.SECONDS,
                                                    new ArrayBlockingQueue<>(5),
                                                    Executors.defaultThreadFactory(),
                                                    new ThreadPoolExecutor.AbortPolicy());

        Future<String> f = pool.submit(new MyCallable(50)); //提交任务返回的Future对象,可以通过调用get方法拿到call方法的值
        System.out.println(f.get());

    }
}

class MyCallable implements Callable<String>{
    private int n;

    public MyCallable(){}

    public MyCallable(int n){
        this.n = n;
    }
    @Override
    public String call() throws Exception {
        int sum = 0;
        for (int i = 0; i < n; i++) {
            sum += n;
        }
        return Thread.currentThread().getName() + "计算结果" + sum;
    }
}

 三、Excutors创建线程池,不适合大型应用

 


public class Test {
    public static void main(String[] args) throws Exception{

        ExecutorService pool = Executors.newFixedThreadPool(10);
        Future<String> f = pool.submit(new MyCallable(50)); 
        System.out.println(f.get());

    }
}

class MyCallable implements Callable<String>{
    private int n;

    public MyCallable(){}

    public MyCallable(int n){
        this.n = n;
    }
    @Override
    public String call() throws Exception {
        int sum = 0;
        for (int i = 0; i < n; i++) {
            sum += n;
        }
        return Thread.currentThread().getName() + "计算结果" + sum;
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

郑*杰

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值