111
hxb
2022-11-24 0a3e07f10937484145f33c7560607b4b2353cb81
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
59
60
package com.mm.android.deviceaddmodule.mobilecommon.AppConsume;
 
import android.os.Process;
 
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.ThreadFactory;
 
public class ThreadPool {
    private volatile static ExecutorService cachedThreadPool;
 
    // 提交线程
    public static Future<?> submit(Runnable mRunnable) {
 
        if (cachedThreadPool == null) {
            synchronized (ExecutorService.class) {
                if (cachedThreadPool == null) {
                    cachedThreadPool = Executors.newFixedThreadPool(Runtime
                            .getRuntime().availableProcessors() * 2,new DefaultFactory());
                }
            }
        }
        return cachedThreadPool.submit(mRunnable);
    }
 
    // 关闭
    public static void shutdown() {
        if (cachedThreadPool != null && !cachedThreadPool.isShutdown())
            cachedThreadPool.shutdown();
        cachedThreadPool = null;
    }
 
    static class DefaultFactory implements ThreadFactory {
 
        @Override
        public Thread newThread(Runnable r) {
 
            Thread thread = new Thread(new FactoryRunnable(r));
 
            return thread;
        }
    }
 
    static class FactoryRunnable implements Runnable {
        Runnable runnable;
 
        public FactoryRunnable(Runnable runnable) {
            this.runnable = runnable;
        }
 
        @Override
        public void run() {
            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
            runnable.run();
        }
 
    }
 
}