ThreadUtils.java
1.99 KB
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
61
62
63
64
package com.ectrip.cyt.utils;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
public class ThreadUtils {
private static ThreadPool instance;
private ThreadUtils() {
}
public static ThreadPool getInstance() {
if (instance == null) {
synchronized (ThreadUtils.class) {
if ((instance == null)) {
int cpuCount = Runtime.getRuntime().availableProcessors(); // 获取cpu数量,即核数
int threadCount = cpuCount * 2 + 1; //线程池中线程的个数---cpu核数*2+1--性能最佳
LogUtil.i("ThreadUtils", "ThreadUtils count == " + threadCount);
instance = new ThreadPool(threadCount, threadCount, 0L);
}
}
}
return instance;
}
public static class ThreadPool {
private int corePoolSize;
private int maximunPoolSize;
private long keepAliveTime;
private ThreadPoolExecutor executor;
public ThreadPool(int corePoolSize, int maximunPoolSize, long keepAliveTime) {
this.corePoolSize = corePoolSize;
this.maximunPoolSize = maximunPoolSize;
this.keepAliveTime = keepAliveTime;
}
public void exeute(Runnable runnable) {
if (executor == null) {
executor = new ThreadPoolExecutor(corePoolSize,
maximunPoolSize, keepAliveTime, TimeUnit.SECONDS,
new LinkedBlockingDeque<Runnable>(),
new ThreadPoolExecutor.AbortPolicy());
}
executor.execute(runnable);
}
public void cancel(Runnable r) {
if (executor != null) {
executor.getQueue().remove(r);
}
}
public void close() {
if (executor != null) {
executor.shutdownNow();
}
}
}
}