admin
2021-05-08 f93ff67ed4681f416a653370aa1e7995a56940ef
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
53
54
55
56
57
58
package com.huawei.android.hms.agent.common;
 
import android.os.Handler;
import android.os.Looper;
 
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
 
/**
 * 线程工具,用于执行线程等
 */
public final class ThreadUtil {
    public static final ThreadUtil INST = new ThreadUtil();
 
    private ExecutorService executors;
 
    private ThreadUtil(){
    }
 
    /**
     * 在线程中执行
     * @param runnable 要执行的runnable
     */
    public void excute(Runnable runnable) {
        ExecutorService executorService = getExecutorService();
        if (executorService != null) {
            // 优先使用线程池,提高效率
            executorService.execute(runnable);
        } else {
            // 线程池获取失败,则直接使用线程
            new Thread(runnable).start();
        }
    }
 
    /**
     * 在主线程中执行
     * @param runnable 要执行的runnable
     */
    public void excuteInMainThread(Runnable runnable){
        new Handler(Looper.getMainLooper()).post(runnable);
    }
 
    /**
     * 获取缓存线程池
     * @return 缓存线程池服务
     */
    private ExecutorService getExecutorService(){
        if (executors == null) {
            try {
                executors = Executors.newCachedThreadPool();
            } catch (Exception e) {
                HMSAgentLog.e("create thread service error:" + e.getMessage());
            }
        }
 
        return executors;
    }
}