天天看点

java开发中几种常见的线程池

<a target="_blank" href="https://docs.oracle.com/javase/8/docs/api/index.html?java/util/concurrent/executors.html">java.util.concurrent:class executors</a>

几种常用的的生成线程池的方法:

<code>newcachedthreadpool</code>

<code>newfixedthreadpool</code>

<code>newscheduledthreadpool</code>

<code>newsinglethreadexecutor</code>

<code>newsinglethreadscheduledexecutor</code>

例子:<code>newfixedthreadpool</code>

单线程<code>newsinglethreadexecutor</code>可用于重启

用线程池启动定时器

例子:类似timer的定时执行

<code>executorservice</code>在<code>executor</code>的基础上增加了一些方法,其中有两个核心的方法:

<code>future&lt;?&gt; submit(runnable task)</code>

<code>&lt;t&gt; future&lt;t&gt; submit(callable&lt;t&gt; task)</code>

这两个方法都是向线程池中提交任务,它们的区别在于<code>runnable</code>在执行完毕后没有结果,<code>callable</code>执行完毕后有一个结果。这在多个线程中传递状态和结果是非常有用的。另外他们的相同点在于都返回一个future对象。<code>future</code>对象可以阻塞线程直到运行完毕(获取结果,如果有的话),也可以取消任务执行,当然也能够检测任务是否被取消或者是否执行完毕。

lock功能类似传统多线程技术里的<code>synchronized</code>,实现线程互斥,但更加面向对象。将需要互斥的代码片段放到<code>lock.lock();</code>和<code>lock.unlock();</code>之间。

例子

读写锁

<a target="_blank" href="https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/locks/reentrantreadwritelock.html">java.util.concurrent.locks:class reentrantreadwritelock</a>

javadoc文档读写锁例子,缓存:

重点注意在释放写锁前加读锁那部分代码,注释为<code>// downgrade by acquiring read lock before releasing write lock</code>。自己挂了写锁,再挂读锁是可以的,这面涉及的技巧以后再研究。

condition类似于传统多线程技术中的<code>object.wait</code>和<code>object.notify</code>,实现线程间同步。

javadoc文档例子,可阻塞队列

<a target="_blank" href="https://docs.oracle.com/javase/8/docs/api/index.html?java/util/concurrent/locks/condition.html">class boundedbuffer例子</a>

使用了两个<code>condition</code>

<code>semaphore</code>

类似占坑

<code>cyclicbarrier</code>

阶段性使进度一致

<code>countdownlatch</code>

一人通知多人/多人通知一人

<code>exchanger</code>

线程间数据交换,都到达则自然交换