线程工具类ThreadUtils

摘要:
1.Pom引入了番石榴依赖<dependency><groupId>com。谷歌。番石榴番石榴23.01.ThreadUtilsimplortcom。谷歌。常见的util。同时发生的螺纹系数Bu
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);

免责声明:文章转载自《线程工具类ThreadUtils》仅用于学习参考。如对内容有疑问,请及时联系本站处理。

上篇Android中Message机制的灵活应用【域渗透】域权限维持下篇

宿迁高防,2C2G15M,22元/月;香港BGP,2C5G5M,25元/月 雨云优惠码:MjYwNzM=

相关文章

RestTemplate请求使用方法

获取restTemplate对象 封装请求头 封装请求参数 发起请求 获取返回值 获取restTemplate对象 1 RestTemplate restTemplate=new RestTemplate(); 封装请求头 HttpHeaders requestHeaders = newHttpHeaders(); //添加session List&...

读取文件将 Excel 文件 转换成 CSV 文件 解决方案

本文纯属个人见解,是对前面学习的总结,如有描述不正确的地方还请高手指正~     考参:     http://www.codeproject.com/Articles/246772/Convert-xlsx-xls-to-csv     http://exceldatareader.codeplex.com/          做法:从excel中把数据...

C# 调用带参数EXE文件及带启动参数EXE制作

(一)、先制作一个带启动参数的EXE文件。  步骤:             1、定义全局私有变量:private string[] s = new string[1];  //这里为了简单起见,只做一个参数            2、  在窗体的构造函数中初始化启动参数               public Form1(string[] p) ...

SpringBoot+读取properties文件内容并注入到类属性中

第一种方法,以发送短信功能为例: 1.application.properties文件: sms.host=http://dingxin.market.alicloudapi.com sms.path=/dx/sendSms sms.method=POST sms.appcode=xxxxxxx 2.需要注入的类,在类的上面加上@Component,在类属...

动态加载与插件系统的初步实现(3):WinForm示例

动态加载与插件系统的初步实现(三):WinForm示例 代码文件在此Download,本文章围绕前文所述默认AppDomain、插件容器AppDomain两个域及IPlugin、PluginProvider、PluginProxy3个类的使用与变化进行。 添加WinForm项目Host、类库Plugin、引用System.Windows.Forms;的类...

Javaweb统计在线人数的小栗子

最近在学习Javaweb相关的内容(不黑不吹之前对web开发零基础),下面通过一个统计在线人数的小栗子讲讲Servlet监听器吧 开发环境 eclipse  tomcat 7 先说说这个小栗子的构思:         首先要考虑的就是通过什么方式能够统计在线人数?很容易想到可以通过session来统计在线人数为什么不是request呢?因为request在...