|
@@ -0,0 +1,70 @@
|
|
|
|
+package com.alvin;
|
|
|
|
+
|
|
|
|
+import java.util.concurrent.*;
|
|
|
|
+import java.util.concurrent.atomic.AtomicInteger;
|
|
|
|
+import java.util.function.Function;
|
|
|
|
+
|
|
|
|
+public class FunUtil {
|
|
|
|
+ // 核心线程数
|
|
|
|
+ public static Integer parallel = 100;
|
|
|
|
+ //自定义线程池,需要设置 最大并发数、 线程池名称
|
|
|
|
+ public static ExecutorService pool = new ThreadPoolExecutor(
|
|
|
|
+ parallel, Integer.MAX_VALUE,
|
|
|
|
+ 60L, TimeUnit.SECONDS,
|
|
|
|
+ new SynchronousQueue<>(), new NamedThreadFactory("测试"));
|
|
|
|
+
|
|
|
|
+ /**
|
|
|
|
+ * 限时函数封装
|
|
|
|
+ *
|
|
|
|
+ * @param param 函数入参
|
|
|
|
+ * @param timeout 超时时间(毫秒)
|
|
|
|
+ * @param function 执行的方法
|
|
|
|
+ * @return
|
|
|
|
+ */
|
|
|
|
+ public static <T, R> Object exec(T param, Integer timeout, Function<T, R> function) {
|
|
|
|
+ Future<R> future = pool.submit(() -> function.apply(param));
|
|
|
|
+ R res = null;
|
|
|
|
+ try {
|
|
|
|
+ res = future.get(timeout, TimeUnit.MILLISECONDS);
|
|
|
|
+ } catch (Exception e) {
|
|
|
|
+ System.out.println("超时处理.");
|
|
|
|
+ }
|
|
|
|
+ return res;
|
|
|
|
+ }
|
|
|
|
+
|
|
|
|
+
|
|
|
|
+ static class NamedThreadFactory implements ThreadFactory {
|
|
|
|
+ private final AtomicInteger poolNumber = new AtomicInteger(1);
|
|
|
|
+
|
|
|
|
+ private final ThreadGroup threadGroup;
|
|
|
|
+
|
|
|
|
+ private final AtomicInteger threadNumber = new AtomicInteger(1);
|
|
|
|
+
|
|
|
|
+ public final String namePrefix;
|
|
|
|
+
|
|
|
|
+ NamedThreadFactory(String name) {
|
|
|
|
+ SecurityManager s = System.getSecurityManager();
|
|
|
|
+ threadGroup = (s != null) ? s.getThreadGroup() :
|
|
|
|
+ Thread.currentThread().getThreadGroup();
|
|
|
|
+ if (null == name || "".equals(name.trim())) {
|
|
|
|
+ name = "pool";
|
|
|
|
+ }
|
|
|
|
+ namePrefix = name + "-" +
|
|
|
|
+ poolNumber.getAndIncrement() +
|
|
|
|
+ "-thread-";
|
|
|
|
+ }
|
|
|
|
+
|
|
|
|
+ @Override
|
|
|
|
+ public Thread newThread(Runnable r) {
|
|
|
|
+ Thread t = new Thread(threadGroup, r,
|
|
|
|
+ namePrefix + threadNumber.getAndIncrement(),
|
|
|
|
+ 0);
|
|
|
|
+ if (t.isDaemon())
|
|
|
|
+ t.setDaemon(false);
|
|
|
|
+ if (t.getPriority() != Thread.NORM_PRIORITY)
|
|
|
|
+ t.setPriority(Thread.NORM_PRIORITY);
|
|
|
|
+ return t;
|
|
|
|
+ }
|
|
|
|
+ }
|
|
|
|
+
|
|
|
|
+}
|