admin
昨天 768498719683f85e5ed19c73eb3d14cdbf420df4
提交 | 用户 | 时间
e57a89 1 package com.jcdm.common.utils;
2
3 import java.util.concurrent.CancellationException;
4 import java.util.concurrent.ExecutionException;
5 import java.util.concurrent.ExecutorService;
6 import java.util.concurrent.Future;
7 import java.util.concurrent.TimeUnit;
8 import org.slf4j.Logger;
9 import org.slf4j.LoggerFactory;
10
11 /**
12  * 线程相关工具类.
13  * 
14  * @author jc
15  */
16 public class Threads
17 {
18     private static final Logger logger = LoggerFactory.getLogger(Threads.class);
19
20     /**
21      * sleep等待,单位为毫秒
22      */
23     public static void sleep(long milliseconds)
24     {
25         try
26         {
27             Thread.sleep(milliseconds);
28         }
29         catch (InterruptedException e)
30         {
31             return;
32         }
33     }
34
35     /**
36      * 停止线程池
37      * 先使用shutdown, 停止接收新任务并尝试完成所有已存在任务.
38      * 如果超时, 则调用shutdownNow, 取消在workQueue中Pending的任务,并中断所有阻塞函数.
39      * 如果仍然超時,則強制退出.
40      * 另对在shutdown时线程本身被调用中断做了处理.
41      */
42     public static void shutdownAndAwaitTermination(ExecutorService pool)
43     {
44         if (pool != null && !pool.isShutdown())
45         {
46             pool.shutdown();
47             try
48             {
49                 if (!pool.awaitTermination(120, TimeUnit.SECONDS))
50                 {
51                     pool.shutdownNow();
52                     if (!pool.awaitTermination(120, TimeUnit.SECONDS))
53                     {
54                         logger.info("Pool did not terminate");
55                     }
56                 }
57             }
58             catch (InterruptedException ie)
59             {
60                 pool.shutdownNow();
61                 Thread.currentThread().interrupt();
62             }
63         }
64     }
65
66     /**
67      * 打印线程异常信息
68      */
69     public static void printException(Runnable r, Throwable t)
70     {
71         if (t == null && r instanceof Future<?>)
72         {
73             try
74             {
75                 Future<?> future = (Future<?>) r;
76                 if (future.isDone())
77                 {
78                     future.get();
79                 }
80             }
81             catch (CancellationException ce)
82             {
83                 t = ce;
84             }
85             catch (ExecutionException ee)
86             {
87                 t = ee.getCause();
88             }
89             catch (InterruptedException ie)
90             {
91                 Thread.currentThread().interrupt();
92             }
93         }
94         if (t != null)
95         {
96             logger.error(t.getMessage(), t);
97         }
98     }
99 }