ThreadUtil工具类

ThreadUtil工具类

public class ThreadUtil{
    private static ThreadUtil _insatnce;
    private static final byte[] wirteLock = new byte[0]; 

    private ThreadPoolExecutor _pool;
    private HashMap<String,Thread> threads = new HashMap<>();

    public interface Task{ void doTask(){} }

    public void init(){get_pool();}     

    public void startThread(final String key , final Task mTask){
        Thread mThread = new Thread(new Runnable(){
                @override
                void run(){
                    mTask.doTask();
                }
            })
        threads.put(key,mThread);
        mThread.start();
    }

    public void finishThread(final String key){
        Thread mThread = threads.get(key);
        mThread.interrput();
        threads.remove(key);
    }

    public void startThreadInPool(final Task mTask){
        if(_pool != null && !_pool.isTerminated()){
            _pool.submit(new Runnable(){
            });
        }
    }

    public bool isMainThread(){
        return Looper.myLooper() == Looper.getMainLooper();
    }

    private ThreadUtil(){}
    public ThreadUtil getInstance(){
        synchronized(wirteLock){
            if( _instance == null ){
                _instance = new ThreadUtil(); 
            }
        }
        return _instance;
    }

    public ThreadPoolExecutor get_pool(){
        synchronized(wirteLock){
            if(_pool == null || _pool.isTerminated){
                _pool = new ThreadPoolExecutor(10,50,3,TimeUnit.MINUTES,new ArrayBlockingQueue<Runnable>(20),new RejectedExecutionHandler(){
                    @Override
                    rejectedExecution(...){
                        handler.postDelayed(new Runnable(){
                            void run(){if(!threadPoolexecutor.isShutdown){

                            threadPoolexecutor.execute(runnable);
                            }}
                        });
                    }
                });
            }
        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值