Java 线程池 ( Thread Pool )

Java 线程池(Thread Pool)是管理和复用多个线程的工具,它可以减少线程创建和销毁的开销,提高应用程序的性能和响应速度。线程池提供了一种机制,可以将多个任务分配给固定数量的线程来执行,从而优化资源使用并提升系统的并发能力。

1. 为什么使用线程池

  • 减少资源消耗:通过重用已创建的线程,避免了频繁创建和销毁线程的开销。
  • 提高响应速度:任务到达时,无需等待新线程的创建即可立即执行。
  • 提高线程管理的可控性:通过统一的管理,方便控制线程数量,避免资源耗尽。

2. 创建线程池

Java 提供了 ExecutorService 接口来表示线程池,通过 Executors 工具类可以方便地创建不同类型的线程池:

  • Fixed Thread Pool:固定大小的线程池。
  • Cached Thread Pool:根据需要创建新线程的线程池。
  • Scheduled Thread Pool:支持定时和周期性任务执行的线程池。
  • Single Thread Executor:单个工作线程的线程池。

3. 使用示例

以下是如何使用 ExecutorServiceExecutors 创建和使用不同类型的线程池的示例:

1. 固定大小线程池 (Fixed Thread Pool)
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class FixedThreadPoolDemo {
    public static void main(String[] args) {
        ExecutorService fixedThreadPool = Executors.newFixedThreadPool(3);

        for (int i = 0; i < 10; i++) {
            fixedThreadPool.execute(() -> {
                System.out.println(Thread.currentThread().getName() + " is executing task.");
                try {
                    Thread.sleep(2000); // 模拟任务执行时间
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            });
        }

        fixedThreadPool.shutdown(); // 关闭线程池
    }
}
2. 缓存线程池 (Cached Thread Pool)
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class CachedThreadPoolDemo {
    public static void main(String[] args) {
        ExecutorService cachedThreadPool = Executors.newCachedThreadPool();

        for (int i = 0; i < 10; i++) {
            cachedThreadPool.execute(() -> {
                System.out.println(Thread.currentThread().getName() + " is executing task.");
                try {
                    Thread.sleep(2000); // 模拟任务执行时间
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            });
        }

        cachedThreadPool.shutdown(); // 关闭线程池
    }
}
3. 单线程执行器 (Single Thread Executor)
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class SingleThreadExecutorDemo {
    public static void main(String[] args) {
        ExecutorService singleThreadExecutor = Executors.newSingleThreadExecutor();

        for (int i = 0; i < 10; i++) {
            singleThreadExecutor.execute(() -> {
                System.out.println(Thread.currentThread().getName() + " is executing task.");
                try {
                    Thread.sleep(2000); // 模拟任务执行时间
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            });
        }

        singleThreadExecutor.shutdown(); // 关闭线程池
    }
}
4. 定时线程池 (Scheduled Thread Pool)
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

public class ScheduledThreadPoolDemo {
    public static void main(String[] args) {
        ScheduledExecutorService scheduledThreadPool = Executors.newScheduledThreadPool(3);

        scheduledThreadPool.scheduleAtFixedRate(() -> {
            System.out.println(Thread.currentThread().getName() + " is executing scheduled task.");
        }, 1, 3, TimeUnit.SECONDS); // 1秒后开始,每3秒执行一次

        // 程序运行一段时间后关闭线程池
        try {
            Thread.sleep(10000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        scheduledThreadPool.shutdown();
    }
}

4. 线程池的管理

  • 提交任务:可以使用 execute 方法提交 Runnable 任务,使用 submit 方法提交 RunnableCallable 任务。
  • 关闭线程池:可以使用 shutdown 方法平滑关闭线程池,使用 shutdownNow 方法立即停止所有任务并关闭线程池。
  • 获取结果:使用 submit 提交的任务会返回一个 Future 对象,通过 Future 可以获取任务的执行结果或取消任务。

5. 自定义线程池

使用 ThreadPoolExecutor 类可以创建自定义的线程池,配置线程池的核心线程数、最大线程数、任务队列和拒绝策略等。

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

public class CustomThreadPoolDemo {
    public static void main(String[] args) {
        ThreadPoolExecutor customThreadPool = new ThreadPoolExecutor(
                2, // 核心线程数
                4, // 最大线程数
                60, // 空闲线程存活时间
                TimeUnit.SECONDS,
                new LinkedBlockingQueue<>(10) // 任务队列
        );

        for (int i = 0; i < 15; i++) {
            customThreadPool.execute(() -> {
                System.out.println(Thread.currentThread().getName() + " is executing task.");
                try {
                    Thread.sleep(2000); // 模拟任务执行时间
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            });
        }

        customThreadPool.shutdown();
    }
}

总结

线程池是管理和复用线程的有效工具,通过使用不同类型的线程池,可以优化资源使用,提升并发性能。通过 ExecutorService 接口和 Executors 工具类,可以方便地创建和管理线程池。对于更高级的需求,可以使用 ThreadPoolExecutor 类自定义线程池配置。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值