亲宝软件园·资讯

展开

Java并发之串行线程池 Java并发之串行线程池实例解析

低调小一 人气:0
想了解Java并发之串行线程池实例解析的相关内容吗,低调小一在本文为您仔细讲解Java并发之串行线程池的相关知识和一些Code实例,欢迎阅读和指正,我们先划重点:java,线程池并发实例,java,线程池使用实例,java,线程池编程实例,下面大家一起来学习吧。

前言

做Android的这两年时间,通过研究Android源码,也会Java并发处理多线程有了自己的一些理解。

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

思路

何为串行线程池呢?

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

既然我们有了思路,那我们就考虑一下所需要的数据结构?

既然是从队列尾部插入Runnable对象,从队列头部执行Runnable对象,我们自然需要一个队列。Java的SDK已经给我们提供了很好的队列数据结构,例如双端队列:ArrayDeque<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

总结

以上就是本文关于Java并发之串行线程池实例解析的全部内容,希望对大家有所帮助。感兴趣的朋友可以继续参阅本站其他相关专题,如有不足之处,欢迎留言指出。感谢朋友们对本站的支持!

加载全部内容

相关教程
猜你喜欢
用户评论