import android.support.annotation.AnyThread;

import android.support.annotation.NonNull;

import android.support.annotation.Nullable;

import android.util.Log;

import java.util.concurrent.BlockingQueue;

import java.util.concurrent.Callable;

import java.util.concurrent.ExecutorService;

import java.util.concurrent.Future;

import java.util.concurrent.LinkedBlockingQueue;

import java.util.concurrent.ThreadPoolExecutor;

import java.util.concurrent.TimeUnit;

/**

* A Singleton thread pool

*/

public class ThreadPool {

private static final String TAG = "ThreadPool";

private static final int KEEP_ALIVE_TIME = 1;

private static volatile ThreadPool sInstance = null;

private static int NUMBER_OF_CORES = Runtime.getRuntime().availableProcessors();

private final ExecutorService mExecutor;

private final BlockingQueue mTaskQueue;

// Made constructor private to avoid the class being initiated from outside

private ThreadPool() {

// initialize a queue for the thread pool. New tasks will be added to this queue

mTaskQueue = new LinkedBlockingQueue<>();

Log.d(TAG, "Available cores: " + NUMBER_OF_CORES);

mExecutor = new ThreadPoolExecutor(NUMBER_OF_CORES, NUMBER_OF_CORES * 2, KEEP_ALIVE_TIME, TimeUnit.SECONDS, mTaskQueue, new SimpleThreadFactory());

}

@NonNull

@AnyThread

public static ThreadPool getInstance() {

if (null == sInstance) {

synchronized (ThreadPool.class) {

if (null == sInstance) {

sInstance = new ThreadPool();

}

}

}

return sInstance;

}

private boolean isThreadPoolAlive() {

return (null != mExecutor) && !mExecutor.isTerminated() && !mExecutor.isShutdown();

}

@Nullable

@AnyThread

public Future submitCallable(@NonNull final Callable c) {

synchronized (this) {

if (isThreadPoolAlive()) {

return mExecutor.submit(c);

}

}

return null;

}

@Nullable

@AnyThread

public Future> submitRunnable(@NonNull final Runnable r) {

synchronized (this) {

if (isThreadPoolAlive()) {

return mExecutor.submit(r);

}

}

return null;

}

/* Remove all tasks in the queue and stop all running threads

*/

@AnyThread

public void shutdownNow() {

synchronized (this) {

mTaskQueue.clear();

if ((!mExecutor.isShutdown()) && (!mExecutor.isTerminated())) {

mExecutor.shutdownNow();

}

}

}

}

Logo

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐