博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
线程池的实现原理
阅读量:7286 次
发布时间:2019-06-30

本文共 2191 字,大约阅读时间需要 7 分钟。

1 package com.test.ThreadPool;  2   3 import java.util.LinkedList;  4 import java.util.List;  5 import java.util.concurrent.atomic.AtomicInteger;  6 /**  7  * 线程池的实现原理  8  * @author Flynn  9  * 10  */ 11 public class ThreadPool { 12     private static ThreadPool pool = null; 13      14     private final int initNum ;    //初始化线程数量 15     private volatile AtomicInteger quenLen = new AtomicInteger(0);    //任务队列长度,volatile修饰的原子操作不必加入同步模块 16     private List
taskQuen = new LinkedList
() ; //待处理任务队列,涉及其的操作要做线程安全处理(使用linkedlist是因为任务队列插入删除操作比较频繁) 17 private workThread[] threads; 18 private ThreadPool(int num){ 19 this.initNum = num ; 20 threads = new workThread[initNum] ; 21 for(int i=0;i
1 package com.test.ThreadPool; 2  3 import java.util.concurrent.atomic.AtomicInteger; 4  5 public class TestMain { 6  7     /** 8      * @param args 9      * @throws InterruptedException 10      */11     public static void main(String[] args) throws InterruptedException {12         // TODO Auto-generated method stub13         ThreadPool pool = ThreadPool.getPool(4) ;14         new TestMain.myRun() ;15         pool.execute(new myRun(),new myRun(),new myRun(),new myRun()) ;16         pool.execute(new myRun(),new myRun(),new myRun(),new myRun()) ;17         pool.execute(new myRun(),new myRun(),new myRun(),new myRun()) ;18         pool.execute(new myRun(),new myRun(),new myRun(),new myRun()) ;19         pool.detory() ;20     }21     static class myRun implements Runnable{22         private static volatile AtomicInteger len = new AtomicInteger(0);    //任务队列长度,原子操作23         @Override24         public void run() {25             // TODO Auto-generated method stub26             System.err.println("任务--"+len.incrementAndGet()+"--执行了");27         }28     }29 }

实验结果:

1 任务--4--执行了 2 任务--3--执行了 3 任务--1--执行了 4 任务--2--执行了 5 任务--7--执行了 6 任务--6--执行了 7 任务--5--执行了 8 任务--10--执行了 9 任务--9--执行了10 任务--8--执行了11 任务--13--执行了12 任务--12--执行了13 任务--11--执行了14 任务--16--执行了15 任务--15--执行了16 任务--14--执行了

可以看到16个任务全部执行了,没有重复,但是打印的顺序不是递增的,那是因为workThread的run()中任务的执行没有放入同步模块,这也就是只管将任务执行但不控制它具体执行的时间

转载于:https://www.cnblogs.com/hfblogs/p/7450066.html

你可能感兴趣的文章
Debian查看启动日志
查看>>
haproxy配置详解以及动静分离的实现
查看>>
1.2 Zookeeper伪集群安装
查看>>
查看客户端域策略应用结果
查看>>
美团外卖Android平台化的复用实践
查看>>
美团即时物流的分布式系统架构设计
查看>>
流行语折射科技新活力
查看>>
Zabbix高级应用二、监控磁盘阵列、Exchange队列、DAG
查看>>
Ubuntu16.04LTS上搭建Sentry
查看>>
oracle查看表空间大小及表数量
查看>>
js 常用提示 console.log & console.info
查看>>
php stdClass 转数组
查看>>
优化NGINX的25种手段
查看>>
svn安装
查看>>
动态容器 数组 api
查看>>
抽取IPA包里的所有图片,包括.car压缩包中的文件
查看>>
DFS lock handle等待事件
查看>>
PowerDesigner 反转Java代码生成类图
查看>>
iOS 分割线设置
查看>>
MyBatis insert 返回主键的方法
查看>>