java 自定义线程池

在Java中,自定义线程池主要是通过实现`java.util.concurrent.ExecutorService`接口来完成的。以下是一个简单的自定义线程池的实现步骤:

1. **创建一个类实现`ExecutorService`接口**:这个类需要实现`execute(Runnable command)`方法,它是用于提交新任务的方法。

2. **定义线程池的基本属性**:如核心线程数、最大线程数、工作队列、线程工厂、拒绝策略等。

3. **创建并启动线程**:根据核心线程数创建线程,并使它们运行,等待工作队列中的任务。

4. **工作线程的运行机制**:工作线程需要不断地从工作队列中获取任务并执行。

5. **任务提交**:当提交新任务时,需要将其添加到工作队列中,并根据当前线程池的状态决定是否需要创建新线程来处理这个任务。

6. **线程池的关闭**:提供关闭线程池的方法,包括优雅关闭和强制关闭。

7. **实现`shutdown`和`shutdownNow`方法**:这些方法用于关闭线程池,不再接受新任务。

以下是一个简单的自定义线程池实现示例:

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.List;
import java.util.ArrayList;

public class CustomThreadPool implements ExecutorService {
    private final ThreadPoolExecutor executor;

    public CustomThreadPool(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue, ThreadFactory threadFactory) {
        this.executor = new ThreadPoolExecutor(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, threadFactory);
    }

    @Override
    public void execute(Runnable command) {
        executor.execute(command);
    }

    @Override
    public void shutdown() {
        executor.shutdown();
        try {
            if (!awaitTermination(60, TimeUnit.SECONDS)) {
                System.out.println("Timeout!");
            }
        } catch (InterruptedException e) {
            System.out.println("Interrupted!");
        }
    }

    @Override
    public List<Runnable> shutdownNow() {
        return executor.shutdownNow();
    }

    @Override
    public boolean isShutdown() {
        return executor.isShutdown();
    }

    @Override
    public boolean isTerminated() {
        return executor.isTerminated();
    }

    @Override
    public boolean awaitTermination(long timeout, TimeUnit unit) throws InterruptedException {
        return executor.awaitTermination(timeout, unit);
    }

    // Custom methods can be added here
}

// Usage example
public class ThreadPoolExample {
    public static void main(String[] args) {
        int corePoolSize = 5;
        int maximumPoolSize = 10;
        long keepAliveTime = 1L;
        TimeUnit unit = TimeUnit.MINUTES;
        BlockingQueue<Runnable> workQueue = new LinkedBlockingQueue<>();
        ThreadFactory threadFactory = Executors.defaultThreadFactory();
        CustomThreadPool customThreadPool = new CustomThreadPool(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, threadFactory);

        // Submit tasks to the custom thread pool
        for (int i = 0; i < 10; i++) {
            int finalI = i;
            customThreadPool.execute(() -> {
                System.out.println("Task " + finalI + " executed by " + Thread.currentThread().getName());
            });
        }

        // Shutdown the custom thread pool
        customThreadPool.shutdown();
    }
}

在这个示例中,`CustomThreadPool` 类包装了 `ThreadPoolExecutor`,实现了 `ExecutorService` 接口,并提供了自定义线程池的基本功能。使用时,可以创建 `CustomThreadPool` 的实例,并像使用标准线程池一样提交任务和关闭线程池。

请注意,这个示例仅用于演示如何自定义线程池,实际应用中可能需要更多的功能和异常处理。
 


ThreadPoolExecutor

`ThreadPoolExecutor` 是 Java 中 `java.util.concurrent` 包下的一个类,它提供了一个线程池的实现,用于管理一组工作线程(work thread)。线程池可以有效地管理线程的生命周期和执行任务,它允许多个线程并发执行,并且可以重复使用这些线程,从而减少因频繁创建和销毁线程而产生的开销。

以下是 `ThreadPoolExecutor` 的一些关键特性和用法:

1. **核心线程数(Core Pool Size)**:线程池中始终存活的线程数量,即使它们处于空闲状态。

2. **最大线程数(Maximum Pool Size)**:线程池允许的最大线程数量。如果任务太多,超出核心线程数的额外任务将使用新创建的线程来执行,直到达到这个最大值。

3. **工作队列(Work Queue)**:一个阻塞队列,用于存储等待执行的任务。

4. **线程工厂(Thread Factory)**:用于创建新线程的工厂。

5. **拒绝策略(Rejected Execution Handler)**:当任务太多来不及处理时,定义了任务队列满了之后的饱和策略,例如丢弃任务或抛出异常。

6. **存活时间(Keep-Alive Time)**:非核心线程空闲时存活的时间,避免长时间保持空闲线程。

7. **时间单位(Time Unit)**:存活时间的时间单位,如秒、毫秒等。

8. **执行任务**:`execute(Runnable command)` 方法用于提交一个任务(实现了 `Runnable` 接口的对象)到线程池中。

9. **提交任务**:`submit(Runnable task)` 方法用于提交一个任务并返回一个 `Future` 对象,可以通过该对象查询任务执行状态或获取结果。

下面是 `ThreadPoolExecutor` 的一个基本使用示例:

import java.util.concurrent.*;

public class ThreadPoolExecutorExample {
    public static void main(String[] args) {
        // 创建一个固定大小的线程池
        int corePoolSize = 5;
        int maximumPoolSize = 10;
        long keepAliveTime = 1L; // 非核心线程空闲存活时间
        TimeUnit unit = TimeUnit.MINUTES; // 时间单位
        BlockingQueue<Runnable> workQueue = new LinkedBlockingQueue<>();
        ThreadFactory threadFactory = Executors.defaultThreadFactory();
        RejectedExecutionHandler handler = new ThreadPoolExecutor.AbortPolicy(); // 拒绝策略

        ThreadPoolExecutor executor = new ThreadPoolExecutor(
                corePoolSize,
                maximumPoolSize,
                keepAliveTime,
                unit,
                workQueue,
                threadFactory,
                handler
        );

        // 提交任务到线程池
        for (int i = 0; i < 10; i++) {
            int finalI = i;
            executor.execute(() -> {
                System.out.println("Task " + finalI + " executed by " + Thread.currentThread().getName());
            });
        }

        // 关闭线程池,不再接受新任务,已提交的任务将完成后关闭
        executor.shutdown();
        try {
            // 等待线程池关闭,所有任务执行完毕
            if (!executor.awaitTermination(60, TimeUnit.SECONDS)) {
                System.out.println("Timeout!");
            }
        } catch (InterruptedException e) {
            System.out.println("Interrupted!");
        }
    }
}

在这个示例中,我们创建了一个具有固定核心线程数和最大线程数的线程池,设置了非核心线程的存活时间和拒绝策略。然后,我们提交了10个任务到线程池中,最后关闭了线程池并等待所有任务执行完毕。

使用线程池可以有效地提高应用程序的响应速度和线程的利用率,同时也简化了线程管理。
 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值