您的位置:首页 > 移动开发 > Android开发

多线程实现方法之一

2016-07-21 00:24 375 查看
一、创建线程池工厂

**

 * 线程池工厂

 */

public class ThreadPoolFactory {

    public static ThreadPoolProxy threadPoolProxy;

    public static final int Common_CORE_POOL_SIZE=5;

    public static final int Common_MAX_POOL_SIZE=5;

    public static final int Common_KEEP_LIVE_TIME=1;

    // 单例模式

    public static ThreadPoolProxy getCommonThreadPool(){

        if(threadPoolProxy==null){

            synchronized (ThreadPoolFactory.class){

                if(threadPoolProxy==null){

                    threadPoolProxy=new ThreadPoolProxy(Common_CORE_POOL_SIZE,Common_MAX_POOL_SIZE,Common_KEEP_LIVE_TIME);

                }

            }

        }

        return threadPoolProxy;

    }

}

二、线程池代理

/**

 *线程池代理

 */

public class ThreadPoolProxy {

    private ThreadPoolExecutor tpx;//线程池执行者

    private int corePoolSize;//线程池数

    private int maximumPoolSize;//最大最小数

    private long keepAliveTime;//活跃时间

    public ThreadPoolProxy(int corePoolSize, int maximumPoolSize, long keepAliveTime) {

        this.corePoolSize = corePoolSize;

        this.maximumPoolSize = maximumPoolSize;

        this.keepAliveTime = keepAliveTime;

    }

    public ThreadPoolExecutor initThreadPoolExecutor(){

        if(tpx == null){

            synchronized (ThreadPoolProxy.class){

                if (tpx == null){

                    BlockingQueue<Runnable> workQueue = new LinkedBlockingDeque<>();//基于链表的双端阻塞队列

                    ThreadFactory threadFactory = Executors.defaultThreadFactory();//默认线程工厂

                    RejectedExecutionHandler handler = new ThreadPoolExecutor.AbortPolicy();

                    tpx = new ThreadPoolExecutor(corePoolSize,maximumPoolSize,keepAliveTime, TimeUnit.SECONDS,workQueue,threadFactory,handler);

                }

            }

        }

        return tpx;

    }

    // 执行任务

    public void execute(Runnable task) {

        initThreadPoolExecutor();

        tpx.execute(task);

    }

    // 移除任务

    public void remove(Runnable task) {

        initThreadPoolExecutor();

        tpx.remove(task);

    }

    // 提交任务(Future+execute(Runnable task))

    public Future<?> summit(Runnable task) {

        initThreadPoolExecutor();

        return tpx.submit(task);

    }

}

三、操作线程

public class ThreadPoolUtils {

    // 在非UI线程中执行

    public static void runTaskInThread(Runnable task){

        ThreadPoolFactory.getCommonThreadPool().execute(task);

    }

    // 在UI线程中执行

    public static Handler handler=new Handler();

    public static void runTaskInUIThread(Runnable task){

        handler.post(task);

    }

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息