建立/銷毀線程開銷大(T1、T3),頻繁創建導致效能低落。線程池將創建/銷毀移至啟動/關閉或閒置時段,並固定線程數量,大幅降低併發請求下的資源消耗。
public class ThreadPoolManager {
private static ThreadPoolManager instance;
private final List<Upload> taskQueue = Collections.synchronizedList(new LinkedList<>());
private final WorkThread[] workQueue;
private static int worker_num = 5;
private ThreadPoolManager() { this(5); }
private ThreadPoolManager(int num) {
worker_num = num;
workQueue = new WorkThread[worker_num];
for (int i = 0; i < worker_num; i++) workQueue[i] = new WorkThread(i);
}
public static synchronized ThreadPoolManager getInstance() {
if (instance == null) instance = new ThreadPoolManager();
return instance;
}
public void addTask(Upload task) {
synchronized (taskQueue) {
if (task != null) {
taskQueue.add(task);
taskQueue.notifyAll();
}
}
}
public void destory() {
for (WorkThread wt : workQueue) wt.stopThread();
synchronized (taskQueue) { taskQueue.clear(); }
}
private class WorkThread extends Thread {
private final int taskId;
private volatile boolean isRuning = true, isWaiting = false;
WorkThread(int id) { this.taskId = id; start(); }
public void stopThread() { isRuning = false; }
@Override public void run() {
while (isRuning) {
Upload temp = null;
synchronized (taskQueue) {
while (isRuning && taskQueue.isEmpty()) {
try { taskQueue.wait(20); } catch (InterruptedException ignored) {}
}
if (isRuning) temp = taskQueue.remove(0);
}
if (temp != null) {
isWaiting = false;
temp.uploadPic();
isWaiting = true;
}
}
}
}
}
public abstract class Upload {
protected String info;
public abstract boolean uploadPic();
public String getInfo() { return info; }
}
public class TaskUpload extends Upload {
public TaskUpload(String info) { this.info = info; }
@Override public boolean uploadPic() {
System.out.println(info + " sleep begin...");
try { Thread.sleep(2000); } catch (InterruptedException e) { e.printStackTrace(); }
System.out.println(info + " sleep end...");
return false;
}
}
public class ThreadPoolManagerTest {
public static void main(String[] args) {
Upload[] tasks = new TaskUpload[7];
for (int i = 0; i < 7; i++) tasks[i] = new TaskUpload("task id is " + i);
ThreadPoolManager pool = ThreadPoolManager.getInstance();
pool.BatchAddTask(tasks);
pool.destory();
}
}