package com.android.common.executors;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * Created by chengzhenyu on 2015/12/9.
 */
public class ThreadExecutor {

    private static ThreadExecutor instance;
    private static ExecutorService executor;

    private static final ThreadFactory sThreadFactory = new ThreadFactory() {

        private final AtomicInteger threadCount = new AtomicInteger(1);

        @Override
        public Thread newThread(Runnable r) {
            return new Thread(r,"My Thread #"+threadCount);
        }
    };

    private ThreadExecutor(){
        executor = Executors.newCachedThreadPool(sThreadFactory);
    }

    public static synchronized ThreadExecutor getInstance(){
        if(instance==null){
            instance = new ThreadExecutor();
        }
        return instance;
    }

    public ExecutorService getExecutor(){
        return executor;
    }

    public void execute(Runnable r){
        executor.execute(r);
    }

    public <T> Future<T> submit(Callable<T> task) {
        return executor.submit(task);
    }

}
