简单工具类


写作初衷:由于日常开发经常需要用到很多工具类,经常根据需求自己写也比较麻烦
网上好了一些工具类例如commom.lang3或者hutool或者Jodd这样的开源工具,但是
发现他们之中虽然设计不错,但是如果我想要使用,就必须要引入依赖并且去维护依赖,有些
甚至会有存在版本编译不通过问题,故此想要写作一个每个类都可以作为独立工具类使用
每个使用者只需要复制该类,到任何项目当中都可以使用,所以需要尊从以下两个原则才能
做到.在此诚邀各位大佬参与.可以把各自用过的工具,整合成只依赖JDK,每个类都能够单独
使用的工具.每个人当遇到业务需求需要使用的时候,只需要到这里单独拷贝一个即可使用.
抛弃传统的需要引入依赖的烦恼.让大家一起来解决你所面临的业务问题吧!


介绍


遵从两大原则



  • 1.绝不依赖JDK以外的源码
  • 2.牺牲代码复用性,每个类都必须是单独的组件,绝不互相引用,做到完全解耦

package *;

import java.util.concurrent.CancellationException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;

/**
* @program: simple_tools
* @description: 线程工具类
* @author: ChenWenLong
* @create: 2019-10-18 13:51
**/
public class ThreadUtils {

/**
* sleep等待,单位为毫秒
*/
public static void sleep(long milliseconds) {
try {
Thread.sleep(milliseconds);
} catch (InterruptedException e) {
return;
}
}

/**
* 停止线程池
* 先使用shutdown, 停止接收新任务并尝试完成所有已存在任务.
* 如果超时, 则调用shutdownNow, 取消在workQueue中Pending的任务,并中断所有阻塞函数.
* 如果仍人超時,則強制退出.
* 另对在shutdown时线程本身被调用中断做了处理.
*/
public static void shutdownAndAwaitTermination(ExecutorService pool) {
if (pool != null && !pool.isShutdown()) {
pool.shutdown();
try {
if (!pool.awaitTermination(120, TimeUnit.SECONDS)) {
pool.shutdownNow();
if (!pool.awaitTermination(120, TimeUnit.SECONDS)) {
System.out.println("Pool did not terminate");
}
}
} catch (InterruptedException ie) {
pool.shutdownNow();
Thread.currentThread().interrupt();
}
}
}

/**
* 打印线程异常信息
*/
public static void printException(Runnable r, Throwable t) {
if (t == null && r instanceof Future<?>) {
try {
Future<?> future = (Future<?>) r;
if (future.isDone()) {
future.get();
}
} catch (CancellationException ce) {
t = ce;
} catch (ExecutionException ee) {
t = ee.getCause();
} catch (InterruptedException ie) {
Thread.currentThread().interrupt();
}
}
if (t != null) {
//此处建议转为日志记录
System.out.println(t.getMessage());
}
}
}