zoukankan      html  css  js  c++  java
  • 线程工具类ThreadUtils

    1.pom引入guava依赖

    <dependency>
          <groupId>com.google.guava</groupId>
          <artifactId>guava</artifactId>
          <version>23.0</version>
    </dependency>
    

    1.线程工具类ThreadUtils

    import com.google.common.util.concurrent.ThreadFactoryBuilder;
    
    import java.lang.management.ManagementFactory;
    import java.lang.management.ThreadInfo;
    import java.lang.management.ThreadMXBean;
    import java.util.concurrent.*;
    
    /**
     * thread utils
     */
    public class ThreadUtils {
    
    
        private static final ThreadMXBean threadBean =  ManagementFactory.getThreadMXBean();
        private static final int STACK_DEPTH = 20;
    
        public static ThreadPoolExecutor newDaemonCachedThreadPool(String prefix){
            ThreadFactory threadFactory = namedThreadFactory(prefix);
            return ((ThreadPoolExecutor) Executors.newCachedThreadPool(threadFactory));
        }
    
        private static ThreadFactory namedThreadFactory(String prefix) {
            return new ThreadFactoryBuilder().setDaemon(true).setNameFormat(prefix + "-%d").build();
        }
    
        public static ThreadPoolExecutor newDaemonCachedThreadPool(String prefix ,
                                                                   int maxThreadNumber,
                                                                   int keepAliveSeconds){
            ThreadFactory threadFactory = namedThreadFactory(prefix);
            ThreadPoolExecutor threadPool = new ThreadPoolExecutor(
                    // corePoolSize: the max number of threads to create before queuing the tasks
                    maxThreadNumber,
                    // maximumPoolSize: because we use LinkedBlockingDeque, this one is not used
                    maxThreadNumber,
                    keepAliveSeconds,
                    TimeUnit.SECONDS,
                    new LinkedBlockingQueue<Runnable>(),
                    threadFactory);
            threadPool.allowCoreThreadTimeOut(true);
            return threadPool;
        }
    
        public static ThreadPoolExecutor newDaemonFixedThreadPool(int nThreads , String prefix){
            ThreadFactory threadFactory = namedThreadFactory(prefix);
            return ((ThreadPoolExecutor) Executors.newFixedThreadPool(nThreads, threadFactory));
        }
    
        public static ExecutorService newDaemonSingleThreadExecutor(String threadName){
            ThreadFactory threadFactory = new ThreadFactoryBuilder()
                    .setDaemon(true)
                    .setNameFormat(threadName)
                    .build();
            return Executors.newSingleThreadExecutor(threadFactory);
        }
    
        public static ExecutorService newDaemonFixedThreadExecutor(String threadName,int threadsNum){
            ThreadFactory threadFactory = new ThreadFactoryBuilder()
                    .setDaemon(true)
                    .setNameFormat(threadName)
                    .build();
            return Executors.newFixedThreadPool(threadsNum, threadFactory);
        }
    
        public static ScheduledExecutorService newDaemonThreadScheduledExecutor(String threadName, int corePoolSize) {
            return newThreadScheduledExecutor(threadName, corePoolSize, true);
        }
    
        public static ScheduledExecutorService newThreadScheduledExecutor(String threadName, int corePoolSize, boolean isDaemon) {
            ThreadFactory threadFactory = new ThreadFactoryBuilder()
                    .setDaemon(isDaemon)
                    .setNameFormat(threadName)
                    .build();
            ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(corePoolSize, threadFactory);
            // By default, a cancelled task is not automatically removed from the work queue until its delay
            // elapses. We have to enable it manually.
            executor.setRemoveOnCancelPolicy(true);
            return executor;
        }
    
        public static ThreadInfo getThreadInfo(Thread t) {
            long tid = t.getId();
            return threadBean.getThreadInfo(tid, STACK_DEPTH);
        }
    
        public static String formatThreadInfo(ThreadInfo threadInfo, String indent) {
            StringBuilder sb = new StringBuilder();
            appendThreadInfo(sb, threadInfo, indent);
            return sb.toString();
        }
    
        public static void appendThreadInfo(StringBuilder sb,
                                            ThreadInfo info,
                                            String indent) {
            boolean contention = threadBean.isThreadContentionMonitoringEnabled();
    
            if (info == null) {
                sb.append(indent).append("Inactive (perhaps exited while monitoring was done)
    ");
                return;
            }
            String taskName = getTaskName(info.getThreadId(), info.getThreadName());
            sb.append(indent).append("Thread ").append(taskName).append(":
    ");
    
            Thread.State state = info.getThreadState();
            sb.append(indent).append("  State: ").append(state).append("
    ");
            sb.append(indent).append("  Blocked count: ").append(info.getBlockedCount()).append("
    ");
            sb.append(indent).append("  Waited count: ").append(info.getWaitedCount()).append("
    ");
            if (contention) {
                sb.append(indent).append("  Blocked time: " + info.getBlockedTime()).append("
    ");
                sb.append(indent).append("  Waited time: " + info.getWaitedTime()).append("
    ");
            }
            if (state == Thread.State.WAITING) {
                sb.append(indent).append("  Waiting on ").append(info.getLockName()).append("
    ");
            } else  if (state == Thread.State.BLOCKED) {
                sb.append(indent).append("  Blocked on ").append(info.getLockName()).append("
    ");
                sb.append(indent).append("  Blocked by ").append(
                        getTaskName(info.getLockOwnerId(), info.getLockOwnerName())).append("
    ");
            }
            sb.append(indent).append("  Stack:").append("
    ");
            for (StackTraceElement frame: info.getStackTrace()) {
                sb.append(indent).append("    ").append(frame.toString()).append("
    ");
            }
        }
    
        private static String getTaskName(long id, String name) {
            if (name == null) {
                return Long.toString(id);
            }
            return id + " (" + name + ")";
        }
    
        public static void sleep(final long millis) {
            try {
                Thread.sleep(millis);
            } catch (final InterruptedException ignore) {}
        }
    }
    

    2.经常使用的工具类方法

    import java.util.concurrent.ThreadPoolExecutor;
    ...
    ThreadPoolExecutor execService = (ThreadPoolExecutor) ThreadUtils.newDaemonFixedThreadExecutor("Executor-Thread", 20);
    
  • 相关阅读:
    JavaScript操作服务器控件之Gridview控件
    GridView_RowDataBound 常用方法
    GridView ,后台修改 跟新完毕,前端 未跟新处理
    怎么判断DropDownList是否选择值
    GridView.SelectedIndex
    DropDownlist数据SelectedIndexChanged触发问题解决
    error:将字符串转换为 uniqueidentifier 时失败
    UniqueIdentifier 数据类型
    在Sql2005中,向表中插入数据时遇到uniqueidentifier列,如何插入数据?
    mysql给id生成uuid
  • 原文地址:https://www.cnblogs.com/PythonOrg/p/13600451.html
Copyright © 2011-2022 走看看