更多内容请关注:

锁清秋
package fuxi.concurrency;
import org.junit.Test;
import java.util.concurrent.*;
import static java.util.concurrent.TimeUnit.SECONDS;
public class ThreadPool {
    private static volatile Executor threadPool;
    
    
    
    public static Executor getThreadPool() {
        if (ThreadPool.threadPool == null) {
            synchronized (ThreadPool.class) {
                if (ThreadPool.threadPool == null) {
                    ThreadPool.threadPool = new ThreadPoolExecutor(1, 2, 0, SECONDS,
                            new LinkedBlockingQueue<Runnable>(100), new ThreadPoolExecutor.AbortPolicy());
                }
            }
        }
        return ThreadPool.threadPool;
    }
    @Test
    public void singletonThreadPoolTest() {
        
        int numberOfTimesTheThreadPoolWasCreated = 10;
        
        int numberOfThreadsCreated = 10;
        while (numberOfTimesTheThreadPoolWasCreated-- > 0) {
            Executor pool = getThreadPool();
            System.out.println("pool = " + pool);
            while (numberOfThreadsCreated-- > 0) {
                pool.execute(() -> {
                    synchronized (this) {
                        System.out.println("I a is Runnable: " + Thread.currentThread().getName());
                        try { SECONDS.sleep(2); } catch (InterruptedException e) { e.printStackTrace(); }
                    }
                });
            }
        }
        
        for (; ; ) {
        }
    }
    
    @Test
    public void runnableCallable() {
        Runnable runnable = () -> System.out.println(" I an is Runnable interface");
        Callable callable = () -> "I an is Callable interface";
    }
}