ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

终止线程池对应某个线程

2022-04-15 12:32:28  阅读:126  来源: 互联网

标签:mThreadPool return 终止 线程 某个 new serial public


加入某个线程池中有多个线程:

  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();

具体实例如下:

复制代码
package com.leolztang.sb.aop.threadpoolT;

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);
            }
        }
        
    }
}
复制代码

 

 

复制代码
package com.leolztang.sb.aop.threadpoolT;

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();
    }
}
复制代码

 

 

   

标签:mThreadPool,return,终止,线程,某个,new,serial,public
来源: https://www.cnblogs.com/exmyth/p/16148521.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有