Java多线程入阶

上传人:飞****9 文档编号:130081933 上传时间:2020-04-24 格式:PPT 页数:32 大小:714.50KB
返回 下载 相关 举报
Java多线程入阶_第1页
第1页 / 共32页
Java多线程入阶_第2页
第2页 / 共32页
Java多线程入阶_第3页
第3页 / 共32页
Java多线程入阶_第4页
第4页 / 共32页
Java多线程入阶_第5页
第5页 / 共32页
点击查看更多>>
资源描述

《Java多线程入阶》由会员分享,可在线阅读,更多相关《Java多线程入阶(32页珍藏版)》请在金锄头文库上搜索。

1、Java多线程入阶 张利飞zhanglifei 内容列表 使用线程的经验 设置名称 响应中断 使用ThreadLocalExecutor ExecutorService和Future阻塞队列 put和take offer和poll drainTo线程间通信 lock condition wait notify notifyAllLock free atomic concurrentMap putIfAbsent CopyOnWriteArrayList关于锁的经验介绍并发流程控制手段 CountDownLatch Barrier定时器 ScheduledExecutorService 大规模定

2、时器TimerWheel并发三大定律图书 相关网络资源 publicclassMyThreadextendsThread publicMyThread super threadname Overridepublicvoidrun TODOSomething MyThreadthread newMyThread thread start Threadthread newThread threadname Overridepublicvoidrun TODOSomething thread start Threadthread newThread Overridepublicvoidrun TOD

3、OSomething thread setName threadname thread start 启动线程的注意事项 无论何种方式 启动一个线程 就需要给它一个名字 这对排错诊断系统有帮助 否则诊断问题时 无法直观知道某个线程的用途 1 2 3 Threadthread newThread task 传入任务thread setName threadname thread start 4 Threadthread newThread task threadname thread start 5 要响应线程中断 thread interrupt Threadthread newThread i

4、nterrupttest Publicvoidrun for TODOSomething if Thread interrupted break thread start Threadthread newThread interrupttest publicvoidrun for try doXXX catch InterruptedExceptione break catch Exceptione handleException thread start Publicvoidfoo throwsInterruptedException if Thread interrupted thrown

5、ewInterruptedException 程序应该对线程中断作出恰当的响应 ThreadLocal 顾名思义它是localvariable 线程局部变量 它的功用非常简单 就是为每一个使用该变量的线程都提供一个变量值的副本 是每一个线程都可以独立地改变自己的副本 而不会和其它线程的副本冲突 从线程的角度看 就好像每一个线程都完全拥有该变量 使用场景Tokeepstatewithathread user id transaction id logging id Tocacheobjectswhichyouneedfrequently隐式传参注意 使用ThreadLocal 一般都是声明在静态

6、变量中 如果不断的创建ThreadLocal而且没有调用其remove方法 将会导致内存泄露 同时请注意 如果是static的ThreadLocal 一般不需要调用remove 任务的提交者和执行者 为了方便并发执行任务 出现了一种专门用来执行任务的实现 也就是Executor 由此 任务提交者不需要再创建管理线程 使用更方便 也减少了开销 java util concurrent Executors是Executor的工厂类 通过Executors可以创建你所需要的Executor 任务的提交者和执行者之间的通讯手段 TaskSubmitter把任务提交给Executor执行 他们之间需要一

7、种通讯手段 这种手段的具体实现 通常叫做Future Future通常包括get 阻塞至任务完成 cancel get timeout 等待一段时间 等等 Future也用于异步变同步的场景 ExecutorServiceexecutor Executors newSingleThreadExecutor Callabletask newCallable publicObjectcall throwsException Objectresult returnresult Futurefuture executor submit task future get 等待至完成 有两种任务 Runna

8、bleCallableCallable是需要返回值的任务 阻塞队列 阻塞队列 是一种常用的并发数据结构 常用于生产者 消费者模式 在Java中 有很多种阻塞队列 ArrayBlockingQueue最常用LinkedBlockingQueue不会满的SynchronousQueuesize为0PriorityBlockingQueueCompletionService BlockingQueue Executor TransferQueue JDK7中更快的SynchronousQueue 使用阻塞队列 使用BlockingQueue的时候 尽量不要使用从Queue继承下来的方法 否则就失去了

9、Blocking的特性了 在BlockingQueue中 要使用put和take 而非offer和poll 如果要使用offer和poll 也是要使用带等待时间参数的offer和poll 使用drainTo批量获得其中的内容 能够减少锁的次数 使用阻塞队列 finalBlockingQueueblockingQ newArrayBlockingQueue 10 Threadthread newThread consumerthread publicvoidrun for Objectobject blockingQ poll 杯具 不等待就会直接返回handle object 1 finalB

10、lockingQueueblockingQ newArrayBlockingQueue 10 Threadthread newThread consumerthread publicvoidrun for try Objectobject blockingQ take 等到有数据才继续handle object catch InterruptedExceptione break catch Exceptione handleexception 2 X 使用阻塞队列 finalBlockingQueueblockingQ newArrayBlockingQueue 10 Threadthread

11、 newThread consumerthread publicvoidrun for try Objectobject blockingQ poll 1 TimeUnit SECONDS 防止死等if object null continue 或者做其他处理 catch InterruptedExceptione break catch Exceptione handleexception 3 3 实现一个简单的阻塞队列 1 classBlockingQ privateObjectnotEmpty newObject privateQueuelinkedList newLinkedList

12、publicObjecttake throwsInterruptedException synchronized notEmpty if linkedList size 0 notEmpty wait returnlinkedList poll publicvoidoffer Objectobject synchronized notEmpty if linkedList size 0 notEmpty notifyAll linkedList add object 要执行wait操作 必须先取得该对象的锁 执行wait操作之后 锁会释放 被唤醒之前 需要先获得锁 要执行notify和noti

13、fyAll操作 都必须先取得该对象的锁 未取得锁就直接执行wait notfiy notifyAll会抛异常 实现一个简单的阻塞队列 2 classBlockingQ privateObjectnotEmpty newObject privateObjectnotFull newObject privateQueuelinkedList newLinkedList privateintmaxLength 10 publicObjecttake throwsInterruptedException synchronized notEmpty if linkedList size 0 notEmp

14、ty wait synchronized notFull if linkedList size maxLength notFull notifyAll returnlinkedList poll publicvoidoffer Objectobject throwsInterruptedException synchronized notEmpty if linkedList size 0 notEmpty notifyAll synchronized notFull if linkedList size maxLength notFull wait linkedList add object

15、 分别需要对notEmpty和notFull加锁 分别需要对notEmpty和notFull加锁 实现一个简单的阻塞队列 3 classBlockingQ privateLocklock newReentrantLock privateConditionnotEmpty lock newCondition privateConditionnotFull lock newCondition privateQueuelinkedList newLinkedList privateintmaxLength 10 publicObjecttake throwsInterruptedException

16、lock lock try if linkedList size 0 notEmpty await if linkedList size maxLength notFull signalAll returnlinkedList poll finally lock unlock publicvoidoffer Objectobject throwsInterruptedException lock lock try if linkedList size 0 notEmpty signalAll if linkedList size maxLength notFull await linkedList add object finally lock unlock 一个锁可以创建多个Condition 要执行await操作 必须先取得该Condition的锁 执行await操作之后 锁会释放 被唤醒之前 需要先获得锁 要执行signal和signalAll操作 都必须先取得该对象的锁 注意 未锁就直接执行await signal siganlAll会抛异常 ReentrantLock和Syn

展开阅读全文
相关资源
相关搜索

当前位置:首页 > IT计算机/网络 > 其它相关文档

电脑版 |金锄头文库版权所有
经营许可证:蜀ICP备13022795号 | 川公网安备 51140202000112号