猎狗模式~~~ 学习了 .
来源:互联网 发布:mysql 更改存放路径 编辑:程序博客网 时间:2024/05/21 04:24
import java.util.concurrent.Callable; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.ThreadFactory; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; public class FuncCourser { private FuncCourser() { } private static ExecutorService executor = Executors .newCachedThreadPool(new ThreadFactory() { int nCount = 0; public Thread newThread(Runnable task) { nCount++; Thread invokeThread = new Thread(task); invokeThread.setName("Invoker-thread-" + nCount); invokeThread.setDaemon(true); return invokeThread; } }); public static void call(Runnable task, TimeUnit unit, long timeout) throws TimeoutException { Future<?> futureResult = executor.submit(task); try { futureResult.get(timeout, unit); } catch (Exception e) { if (e instanceof TimeoutException) { throw new TimeoutException("invoke timeout!"); } throw new RuntimeException(e); } } public static <T> T call(Callable<?> task, TimeUnit unit, long timeout) throws TimeoutException { Future<?> futureResult = executor.submit(task); Object callRet = null; try { callRet = futureResult.get(timeout, unit); } catch (Exception e) { if (e instanceof TimeoutException) { throw new TimeoutException("invoke timeout!"); } throw new RuntimeException(e); } return (T) callRet; } }