Java并发之串行线程池

本文介绍了一种串行线程池的设计与实现方法。通过使用ArrayDeque作为任务队列和ThreadPoolExecutor作为线程池,确保了任务按顺序执行。文章还提供了完整的示例代码。

目录


前言

2016新年和两个小伙伴聊天的时候,提到了多线程排队的问题。也就是说,当服务器一个应用需要同时处理大量线程时,最好有个排队的机制,防止出现大并发失败的情况。

研究生阶段我也是服务器开发,所以对这块也很感兴趣。同时,做Android的这两年时间,通过研究Android源码,也会Java并发处理多线程有了自己的一些理解。

那么问题来了,如何实现一个串行的线程池呢?


思路

何为串行线程池呢?
也就是说,我们的Runnable对象应该有个排队的机制,它们顺序从队列尾部进入,并且从队列头部选择Runnable进行执行。

既然我们有了思路:
1. 那我们就考虑一下所需要的数据结构?
既然是从队列尾部插入Runnable对象,从队列头部执行Runnable对象,我们自然需要一个队列。Java的SDK已经给我们提供了很好的队列数据结构,例如双端队列:ArrayDeque<Runnable>。

  1. 因为涉及到线程的执行,那我们首先就需要有一个合适的线程池,使用ThreadPoolExecutor类即可构造。

  2. 既然是串行执行,那如何保持串行机制呢?
    我们可以通过try和finally机制,我们将传入的Runnable对象重新封装成一个新的Runnable对象,在新的Runnable的run方法的try块中执行Runnable的run方法,在finally中调用执行队列头部Runnable对象出队列,并放入线程池执行的方法。


示例代码

import java.util.ArrayDeque;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * Created by wzy on 16-1-5.
 */
public class SerialExecutor {
    private Runnable mActive;
    private ArrayDeque<Runnable> mArrayDeque = new ArrayDeque<>();

    private static final int CPU_COUNT = Runtime.getRuntime().availableProcessors();
    private static final int CORE_POOL_SIZE = CPU_COUNT + 1;
    private static final int MAXIMUM_POOL_SIZE = CPU_COUNT * 2 + 1;
    private static final int KEEP_ALIVE = 1;
    private static final BlockingQueue<Runnable> sPoolWorkQueue =
            new LinkedBlockingDeque<>(128);
    private static final ThreadFactory sThreadFactory = new ThreadFactory() {
        private final AtomicInteger mCount = new AtomicInteger(1);
        @Override
        public Thread newThread(Runnable r) {
            return new Thread(r, "Serial thread #" + mCount.getAndIncrement());
        }
    };
    private static final ThreadPoolExecutor THREAD_EXECUTOR = new ThreadPoolExecutor(CORE_POOL_SIZE,
            MAXIMUM_POOL_SIZE, KEEP_ALIVE, TimeUnit.SECONDS, sPoolWorkQueue, sThreadFactory);

    public synchronized void execute(final Runnable r) {
        mArrayDeque.offer(new Runnable() {
            @Override
            public void run() {
                try {
                    r.run();
                } finally {
                    scheduleNext();
                }
            }
        });
        // 第一次入队列时mActivie为空,因此需要手动调用scheduleNext方法
        if (mActive == null) {
            scheduleNext();
        }
    }

    private void scheduleNext() {
        if ((mActive = mArrayDeque.poll()) != null) {
            THREAD_EXECUTOR.execute(mActive);
        }
    }

    public static void main(String[] args) {
        SerialExecutor serialExecutor = new SerialExecutor();
        for (int i = 0; i < 10; i ++) {
            final int j = i;
            serialExecutor.execute(new Runnable() {
                @Override
                public void run() {
                    System.out.println("The num is :" + (j + 1));
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            });
        }
    }
}

执行结果如下:

The num is :1
The num is :2
The num is :3
The num is :4
The num is :5
The num is :6
The num is :7
The num is :8
The num is :9
The num is :10
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

低调小一

您的鼓励是我创作最大的动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值