当前位置: 首页 > news >正文

面试手撕代码-手写线程池(优雅打断版本)

手写线程池(优雅打断版本)

package com.study.handcode;import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;public class 手写简单线程池_优雅打断版本 {public static void main(String[] args) throws InterruptedException {HandleWriteSimpleThreadPool pool = new HandleWriteSimpleThreadPool(5);for (int i = 0; i < 10; i++) {final int a = i;pool.execute(() -> {System.out.println("任务:" + a);try {Thread.sleep(1000);System.out.println("任务:" + a + "执行完毕");} catch (InterruptedException e) {
//                    e.printStackTrace();Thread.currentThread().interrupt();  // Thread会清除打断标记,重新标记上}});}Thread.sleep(1500);pool.close();}public static class HandleWriteSimpleThreadPool{private int size;private BlockingQueue<Runnable> queue;private List<Thread> threads = new ArrayList<>();public HandleWriteSimpleThreadPool(int size){this.size = size;this.queue = new ArrayBlockingQueue<>(size);this.start();}public void execute(Runnable task){if (!queue.offer(task))reject();}private void reject() {System.out.println("线程池已满");}// 创建线程,并执行任务private void start() {for (int i = 0; i < size; i++){Thread thread = new Thread(() -> {Thread currentThread = Thread.currentThread();while (true) {   // 判断是否被打断try {if (currentThread.isInterrupted()){System.out.println("被打断,料理后事");break;}Runnable take = queue.take();take.run();} catch (InterruptedException e) {System.out.println("被打断");Thread.currentThread().interrupt(); // 重新标记为被打断状态}}});threads.add(thread);thread.start();}}public void close(){threads.forEach(Thread::interrupt);  // 利用interrupt进行打断}}
}

http://www.mrgr.cn/news/43229.html

相关文章:

  • 【论文速看】DL最新进展20241005-Transformer、目标跟踪、Diffusion Transformer
  • [python]Flask_Login
  • 一、走进新语言
  • DatePicker 日期控件
  • Python 工具库每日推荐 【Pandas】
  • 【智能算法应用】蒲公英优化算法求解二维路径规划问题
  • etcd 集群搭建【docker-compose】
  • TMGM:黄金价格持稳,而WTI原油价格和天然气价格飙升
  • 【C#生态园】提高开发效率:6种必备C#开发库全面解析
  • 【操作系统】引导(Boot)电脑的奇妙开机过程
  • django华业社区电子政务管理系统-计算机毕业设计源码33448
  • 69. x 的平方根
  • 计算机网络:物理层 —— 物理层概述
  • java目录总结
  • 平衡二叉搜索树之 AVL 树的模拟实现【C++】
  • java基础知识点
  • Spring Boot大学生就业招聘系统的架构与实现
  • 6个解决找不到msvcr100.dll,无法继续执行代码的方法
  • C语言指针plus版练习
  • 0.计网和操作系统