侧边栏壁纸
  • 累计撰写 49 篇文章
  • 累计创建 23 个标签
  • 累计收到 0 条评论

目 录CONTENT

文章目录

Java线程池的5种状态

阿砖
2024-04-28 / 0 评论 / 0 点赞 / 94 阅读 / 4355 字

Java线程池的状态共有五种,它们分别是:

  1. RUNNING运行状态,这是线程池的初始状态,能够接受新任务和处理已添加的任务。

  2. SHUTDOWN关闭状态,调用线程池的shutdown()方法会使线程池进入该状态。线程池不再接受新任务,但会继续处理阻塞队列中的任务。

  3. STOP停止状态,调用线程池的shutdownNow()方法会使线程池进入该状态。线程池不再接受新任务,也不会处理阻塞队列中的任务,并且会尝试中断正在执行的任务。

  4. TIDYING整理状态,当所有任务都已终止,线程池会进入该状态。terminated()钩子方法会被很快调用。

  5. TERMINATED销毁状态,执行Terminated()方法。这是一个钩子方法,以便我们可以在ThreadPool终止时进行一些处理。 以上这些状态的变化过程是顺序的,即一个状态结束后,线程池会进入下一个状态,直到最终达到 TERMINATED 状态。

创建线程池的方法

1. 使用 Executors 创建线程

阿里巴巴开发手册并不推荐用这种方法,如果你自己测试的时候倒是可以快速使用一下。

Pasted image 20240703080743.png

public class ThreadPoolExample {
    public static void main(String[] args) {
        // 创建固定大小的线程池
        ExecutorService executorService = Executors.newFixedThreadPool(4);

        // 提交任务到线程池
        for (int i = 0; i < 10; i++) {
            final int taskId = i;
            executorService.execute(() -> {
                System.out.println("Running task " + taskId + " on thread " + Thread.currentThread().getName());
                // 执行任务相关的代码
            });
        }

        // 关闭线程池
        executorService.shutdown();
    }
}

2.使用 ThreadPoolExecutor 创建


public class CustomThreadPoolExample {
    public static void main(String[] args) {
        // 创建自定义线程池
        ThreadPoolExecutor executor = new ThreadPoolExecutor(
            2, // 核心线程数
            4, // 最大线程数
            60, // 线程空闲时间
            TimeUnit.SECONDS, // 线程空闲时间单位
            new ArrayBlockingQueue<>(10) // 任务队列
        );

        // 提交任务和关闭线程池的代码与上面的例子相同
        
    }
}

上面代码中我提交任务使用的是 execute() ,也可以用 submit() 。这两个区别就在于在于 execute 只是简单地启动任务,而 submit 返回一个 Future 对象来管理任务。

如果使用 submit 可以实现下面的代码

public class Main {
	public static void main(String[] args) {
		// 创建固定大小的线程池
		ExecutorService executorService = Executors.newFixedThreadPool(4);

		// 提交任务到线程池
		for (int i = 0; i < 10; i++) {
			final int taskId = i;
			Future<?> submit = executorService.submit(() -> {
				try {
					TimeUnit.SECONDS.sleep(2);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
				System.out.println("Running task " + taskId + " on thread " + Thread.currentThread().getName());
				// 执行任务相关的代码
			});
			// 如果 i == 2 则取消掉这个线程
			if (i == 2) {
				submit.cancel(true);
			}
		}

		// 关闭线程池
		executorService.shutdown();
	}
}

结果就变成了

// 其中的 task 2 被干掉了
Running task 4 on thread pool-1-thread-3
Running task 3 on thread pool-1-thread-4
Running task 1 on thread pool-1-thread-2
Running task 0 on thread pool-1-thread-1
Running task 5 on thread pool-1-thread-3
Running task 6 on thread pool-1-thread-4
Running task 8 on thread pool-1-thread-1
Running task 7 on thread pool-1-thread-2
Running task 9 on thread pool-1-thread-3

0

评论区