几种推荐方式:(例子是获取线程池)
1.饿汉式(一般就用饿汉式就行了,如果非要懒加载那就看下面):
public class ThreadPoolUtil{
private static BlockingQueue<Runnable> bqueue = new ArrayBlockingQueue<Runnable>(100);
private static final int SIZE_CORE_POOL = 5;
private static final int SIZE_MAX_POOL = 100;
private static final long ALIVE_TIME = 2000;
private static ThreadPoolExecutor pool = new ThreadPoolExecutor(SIZE_CORE_POOL, SIZE_MAX_POOL, ALIVE_TIME
, TimeUnit.MILLISECONDS, bqueue, new ThreadPoolExecutor.CallerRunsPolicy());
private ThreadPoolUtil(){ }
static {
pool.prestartAllCoreThreads();
}
public static ThreadPoolExecutor getPool() {
return pool;
}
}
2.懒汉式(注意双重锁加可见性):
public class ThreadPoolUtil{
private static BlockingQueue<Runnable> bqueue = new ArrayBlockingQueue<Runnable>(100);
private static final int SIZE_CORE_POOL = 5;
private static final int SIZE_MAX_POOL = 100;
private static final long ALIVE_TIME = 2000;
private static volatile ThreadPoolExecutor pool;
private ThreadPoolUtil() {
}
public static ThreadPoolExecutor getPool() {
if (bqueue == null) {
synchronized (ThreadPoolUtil.class) {
if (bqueue == null) {
pool = new ThreadPoolExecutor(SIZE_CORE_POOL, SIZE_MAX_POOL, ALIVE_TIME
, TimeUnit.MILLISECONDS, bqueue, new ThreadPoolExecutor.CallerRunsPolicy());
pool.prestartAllCoreThreads();
return pool;
}
}
}
return pool;
}
}
3.枚举类实现(也是比较推荐):
public enum ThreadPoolUtil {
POOL;
private ThreadPoolExecutor pool;
ThreadPoolUtil() {
BlockingQueue<Runnable> bqueue = new ArrayBlockingQueue<Runnable>(100);
final int SIZE_CORE_POOL = 5;
final int SIZE_MAX_POOL = 100;
final long ALIVE_TIME = 2000;
pool = new ThreadPoolExecutor(SIZE_CORE_POOL, SIZE_MAX_POOL, ALIVE_TIME
, TimeUnit.MILLISECONDS, bqueue, new ThreadPoolExecutor.CallerRunsPolicy());
pool.prestartAllCoreThreads();
}
public ThreadPoolExecutor getPool() {
return pool;
}
}
4.静态内部类(也很推荐):
public class ThreadPoolUtil {
private static BlockingQueue<Runnable> bqueue = new ArrayBlockingQueue<Runnable>(100);
private static final int SIZE_CORE_POOL = 5;
private static final int SIZE_MAX_POOL = 100;
private static final long ALIVE_TIME = 2000;
private static volatile ThreadPoolExecutor pool;
private ThreadPoolUtil() {
}
private static class SingletonHolder{
private static ThreadPoolExecutor pool =
new ThreadPoolExecutor(SIZE_CORE_POOL, SIZE_MAX_POOL, ALIVE_TIME
, TimeUnit.MILLISECONDS, bqueue, new ThreadPoolExecutor.CallerRunsPolicy());
static {
pool.prestartAllCoreThreads();
}
}
public static ThreadPoolExecutor getPool() {
return SingletonHolder.pool;
}
}