加入某个线程池中有多个线程:
ThreadPool.addThread(t1);
ThreadPool.addThread(t2);
...
ThreadPool.addThread(tn);
现在想终止第m个线程做法思想如下:
①创建一个hashMap,将所创建的线程以及对应每个线程唯一标识放进去:consoleThreadMap.put(serial, Thread.currentThread());
②在线程正常执行结束后从hashMap中移除:consoleThreadMap.remove(serial);
③如果需要移除的线程m在正常运行中需要移除,则执行consoleThreadMap.get(serial).interrupt();
具体实例如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 | import java.util.Date; import java.util.concurrent.ConcurrentHashMap; import org.springframework.stereotype.Service; @Service public class WebConsoleService { final static String shutdown = "shutdown" ; public static ConcurrentHashMap<String, Thread> consoleThreadMap = new ConcurrentHashMap<String, Thread>(); //创建hashmap,用于存储线程 public void webConsole(String serial, String cmd, int msgid) { try { if (!cmd.equalsIgnoreCase( "shutdown" )){ //如果不是终止指令则通过线程池创建线程 ThreadPoolManager.getInstance().addExecuteTask( new EachT(cmd,serial)); } else { consoleThreadMap.get(serial).interrupt(); //如果是终止指令,则执行interrupt()终止指定的某条线程,这里具体线程通过serial指定 } } catch (Exception e) { } } private class EachT implements Runnable{ private String cmd; private String serial; public EachT(String cmd,String serial) { this .cmd=cmd; this .serial=serial; } @Override public void run() { try { consoleThreadMap.put(serial, Thread.currentThread()); execute(cmd); } catch (Exception e) { } finally { consoleThreadMap.remove(serial); //执行完成后,将线程从hashmap中移除 } } public void execute(String cmd) throws InterruptedException { while (!Thread.currentThread().isInterrupted() && true ) { System.out.println( "ddddddddddddddd" + new Date()); Thread.currentThread().sleep( 2000 ); } } } } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 | import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; import org.springframework.scheduling.concurrent.CustomizableThreadFactory; public final class ThreadPoolManager { private static ThreadPoolManager sThreadPoolManager = new ThreadPoolManager(); // 线程池维护线程的最少数量 private static final int SIZE_CORE_POOL = 50 ; // 线程池维护线程的最大数量 private static final int SIZE_MAX_POOL = 100 ; /* * 线程池单例创建方法 */ public static ThreadPoolManager getInstance() { return sThreadPoolManager; } /************************************************************************************************************** * 常见的几种线程技术 ************************************************************************************************************** * Java通过Executors提供四种线程池,分别为: * newCachedThreadPool创建一个可缓存线程池,如果线程池长度超过处理需要,可灵活回收空闲线程,若无可回收,则新建线程。 * newFixedThreadPool 创建一个定长线程池,可控制线程最大并发数,超出的线程会在队列中等待。 * newScheduledThreadPool 创建一个定长线程池,支持定时及周期性任务执行。 newSingleThreadExecutor * 创建一个单线程化的线程池,它只会用唯一的工作线程来执行任务,保证所有任务按照指定顺序(FIFO, LIFO, 优先级)执行。 * * 1、public static ExecutorService newFixedThreadPool(int nThreads) { * return new ThreadPoolExecutor(nThreads, nThreads, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>()); } * * 2、 public static ExecutorService newSingleThreadExecutor() { * return new FinalizableDelegatedExecutorService (new ThreadPoolExecutor(1, 1, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>())); } * * 3、public static ExecutorService newCachedThreadPool() { * return new ThreadPoolExecutor(0, Integer.MAX_VALUE, 60L, TimeUnit.SECONDS, new SynchronousQueue<Runnable>()); } ****************************************************************************************************************/ /** * 线程池 * * @param corePoolSize - 池中所保存的线程数,包括空闲线程。 * @param maximumPoolSize - 池中允许的最大线程数。 * @param keepAliveTime - 当线程数大于核心时,此为终止前多余的空闲线程等待新任务的最长时间。 * @param unit - keepAliveTime 参数的时间单位。 * @param workQueue - 执行前用于保持任务的队列。此队列仅由保持 execute 方法提交的 Runnable 任务。 * @param handler - 由于超出线程范围和队列容量而使执行被阻塞时所使用的处理程序。 */ // 实质就是newFixedThreadPool 创建一个定长线程池,可控制线程最大并发数,超出的线程会在队列中等待 private final ThreadPoolExecutor mThreadPool = new ThreadPoolExecutor(SIZE_CORE_POOL, SIZE_MAX_POOL, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>(), new CustomizableThreadFactory( "CTSPOOL-THREAD-" ), new ThreadPoolExecutor.AbortPolicy()); /* * 将构造方法访问修饰符设为私有,禁止任意实例化。 */ private ThreadPoolManager() { prepare(); } /* * 将线程池初始化,核心线程数量 */ private void prepare() { if (mThreadPool.isShutdown() && !mThreadPool.prestartCoreThread()) { @SuppressWarnings ( "unused" ) int startThread = mThreadPool.prestartAllCoreThreads(); } } /* * 向线程池中添加任务方法 */ public void addExecuteTask(Runnable task) { if (task != null ) { mThreadPool.execute(task); } } /* * 判断是否是最后一个任务 */ protected boolean isTaskEnd() { if (mThreadPool.getActiveCount() == 0 ) { return true ; } else { return false ; } } /* * 获取缓存大小 */ public int getQueue() { return mThreadPool.getQueue().size(); } /* * 获取线程池中的线程数目 */ public int getPoolSize() { return mThreadPool.getPoolSize(); } /* * 获取已完成的任务数 */ public long getCompletedTaskCount() { return mThreadPool.getCompletedTaskCount(); } /* * 关闭线程池,不在接受新的任务,会把已接受的任务执行玩 */ public void shutdown() { mThreadPool.shutdownNow(); } } |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· DeepSeek 开源周回顾「GitHub 热点速览」
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了