危化品全生命周期管理后端
kongzy
2024-08-22 0c73654f55844e34772732914af8cc1e247aab63
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
package com.gkhy.hazmat.common.utils;
 
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
 
import java.util.concurrent.*;
 
/**
 * 线程相关工具类
 */
@Slf4j
public class Threads {
    private static final Logger logger = LoggerFactory.getLogger(Threads.class);
    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 e){
                t=e;
            } catch (ExecutionException e) {
                t=e.getCause();
            }catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
        }
        if(t!=null){
            logger.error(t.getMessage(),t);
        }
    }
 
 
    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)){
                        log.info("Pool did not terminate");
                    }
                }
            }catch (InterruptedException ie){
                pool.shutdownNow();
                Thread.currentThread().interrupt();
            }
        }
    }
}