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

作者:低调小一 时间:2023-01-07 18:35:54 

前言

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

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

思路

何为串行线程池呢?

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

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

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

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

  • 既然是串行执行,那如何保持串行机制呢?我们可以通过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

来源:http://blog.csdn.net/wzy_1988/article/details/50461242

标签:java,线程池,并发
0
投稿

猜你喜欢

  • Go Java算法之从英文中重建数字示例详解

    2023-10-25 02:37:26
  • JAVA中的日期时间类用法总结

    2023-08-29 08:00:24
  • Eclipse代码格式化设置简单介绍

    2023-10-26 21:59:31
  • C#中const用法详解

    2021-08-12 15:30:29
  • Java编程实现对十六进制字符串异或运算代码示例

    2023-11-06 15:58:15
  • Java根据ip地址获取归属地实例详解

    2023-11-25 06:24:38
  • springboot ErrorPageFilter的实际应用详解

    2023-11-24 01:02:59
  • Android 开发程序锁应用简单实例

    2021-10-07 07:41:34
  • 一篇文章看懂Java异常处理

    2023-10-07 12:08:37
  • 解决Springboot @Autowired 无法注入问题

    2022-04-14 21:19:01
  • java web实现分页查询实例方法

    2022-12-18 18:07:57
  • Android studio 快速删除无用资源的方法

    2022-10-06 20:53:42
  • java实现打砖块小游戏

    2021-07-26 14:47:11
  • 面试Spring中的bean线程是否安全及原因

    2021-06-11 18:25:38
  • java并发编程工具类JUC之ArrayBlockingQueue

    2023-07-04 21:02:20
  • Unity制作小地图和方向导航

    2023-02-07 16:51:02
  • Android自定义ProgressDialog进度等待框

    2022-07-09 13:51:46
  • Springboot自带定时任务实现动态配置Cron参数方式

    2023-11-10 10:21:31
  • Flowable执行完毕的流程查找方法

    2023-01-30 08:53:36
  • java操作excel表格详解

    2021-08-20 14:35:46
  • asp之家 软件编程 m.aspxhome.com