終止線程池對應某個線程


加入某個線程池中有多個線程:

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

具體實例如下:

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

  

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

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM