JDK5中的一个亮点就是将Doug Lea的并发库引入到Java标准库中。Doug Lea确实是一个牛人,能教书,能出书,能编码,不过这在国外仍是比较广泛的,而国内的教授们就相差太远了。
通常的服务器都须要线程池,好比Web、FTP等服务器,不过它们通常都本身实现了线程池,好比之前介绍过的Tomcat、Resin和Jetty等,如今有了JDK5,咱们就没有必要重复造车轮了,直接使用就能够,况且使用也很方便,性能也很是高。java
- package concurrent;
- import java.util.concurrent.ExecutorService;
- import java.util.concurrent.Executors;
- public class TestThreadPool {
- public static void main(String args[]) throws InterruptedException {
-
- ExecutorService exec = Executors.newFixedThreadPool(2 );
- for ( int index = 0 ; index < 100 ; index++) {
- Runnable run = new Runnable() {
- public void run() {
- long time = ( long ) (Math.random() * 1000 );
- System.out.println(“Sleeping ” + time + “ms”);
- try {
- Thread.sleep(time);
- } catch (InterruptedException e) {
- }
- }
- };
- exec.execute(run);
- }
-
- exec.shutdown();
- }
- }
上面是一个简单的例子,使用了2个大小的线程池来处理100个线程。但有一个问题:在for循环的过程当中,会等待线程池有空闲的线程,因此主线程 会阻塞的。为了解决这个问题,通常启动一个线程来作for循环,就是为了不因为线程池满了形成主线程阻塞。不过在这里我没有这样处理。[重要修正:通过 测试,即便线程池大小小于实际线程数大小,线程池也不会阻塞的,这与Tomcat的线程池不一样,它将Runnable实例放到一个“无限”的 BlockingQueue中,因此就不用一个线程启动for循环,Doug Lea果真厉害]
另外它使用了Executors的静态函数生成一个固定的线程池,顾名思义,线程池的线程是不会释放的,即便它是Idle。这就会产生性能问题, 好比若是线程池的大小为200,当所有使用完毕后,全部的线程会继续留在池中,相应的内存和线程切换(while(true)+sleep循环)都会增 加。若是要避免这个问题,就必须直接使用ThreadPoolExecutor()来构造。能够像Tomcat的线程池同样设置“最大线程数”、“最小线 程数”和“空闲线程keepAlive的时间”。经过这些能够基本上替换Tomcat的线程池实现方案。
须要注意的是线程池必须使用shutdown来显式关闭,不然主线程就没法退出。shutdown也不会阻塞主线程。
许多长时间运行的应用有时候须要定时运行任务完成一些诸如统计、优化等工做,好比在电信行业中处理用户话单时,须要每隔1分钟处理话单;网站天天 凌晨统计用户访问量、用户数;大型超时凌晨3点统计当天销售额、以及最热卖的商品;每周日进行数据库备份;公司每月的10号计算工资并进行转账等,这些 都是定时任务。经过 java的并发库concurrent能够轻松的完成这些任务,并且很是的简单。web
- package concurrent;
- import static java.util.concurrent.TimeUnit.SECONDS;
- import java.util.Date;
- import java.util.concurrent.Executors;
- import java.util.concurrent.ScheduledExecutorService;
- import java.util.concurrent.ScheduledFuture;
- public class TestScheduledThread {
- public static void main(String[] args) {
- final ScheduledExecutorService scheduler = Executors
- .newScheduledThreadPool(2 );
- final Runnable beeper = new Runnable() {
- int count = 0 ;
- public void run() {
- System.out.println(new Date() + ” beep ” + (++count));
- }
- };
-
- final ScheduledFuture beeperHandle = scheduler.scheduleAtFixedRate(
- beeper, 1 , 2 , SECONDS);
-
- final ScheduledFuture beeperHandle2 = scheduler
- .scheduleWithFixedDelay(beeper, 2 , 5 , SECONDS);
-
- scheduler.schedule(new Runnable() {
- public void run() {
- beeperHandle.cancel(true );
- beeperHandle2.cancel(true );
- scheduler.shutdown();
- }
- }, 30 , SECONDS);
- }
- }
为了退出进程,上面的代码中加入了关闭Scheduler的操做。而对于24小时运行的应用而言,是没有必要关闭Scheduler的。
在实际应用中,有时候须要多个线程同时工做以完成同一件事情,并且在完成过程当中,每每会等待其余线程都完成某一阶段后再执行,等全部线程都到达某一个阶段后再统一执行。
好比有几个旅行团须要途经深圳、广州、韶关、长沙最后到达武汉。旅行团中有自驾游的,有徒步的,有乘坐旅游大巴的;这些旅行团同时出发,而且每到一个目的地,都要等待其余旅行团到达此地后再同时出发,直到都到达终点站武汉。
这时候CyclicBarrier就能够派上用场。CyclicBarrier最重要的属性就是参与者个数,另外最要方法是await()。当全部线程都调用了await()后,就表示这些线程均可以继续执行,不然就会等待。算法
- package concurrent;
- import java.text.SimpleDateFormat;
- import java.util.Date;
- import java.util.concurrent.BrokenBarrierException;
- import java.util.concurrent.CyclicBarrier;
- import java.util.concurrent.ExecutorService;
- import java.util.concurrent.Executors;
- public class TestCyclicBarrier {
-
- private static int [] timeWalk = { 5 , 8 , 15 , 15 , 10 };
-
- private static int [] timeSelf = { 1 , 3 , 4 , 4 , 5 };
-
- private static int [] timeBus = { 2 , 4 , 6 , 6 , 7 };
-
- static String now() {
- SimpleDateFormat sdf = new SimpleDateFormat(“HH:mm:ss”);
- return sdf.format( new Date()) + “: “;
- }
-
- static class Tour implements Runnable {
- private int [] times;
- private CyclicBarrier barrier;
- private String tourName;
- public Tour(CyclicBarrier barrier, String tourName, int [] times) {
- this .times = times;
- this .tourName = tourName;
- this .barrier = barrier;
- }
- public void run() {
- try {
- Thread.sleep(times[0 ] * 1000 );
- System.out.println(now() + tourName + ” Reached Shenzhen”);
- barrier.await();
- Thread.sleep(times[1 ] * 1000 );
- System.out.println(now() + tourName + ” Reached Guangzhou”);
- barrier.await();
- Thread.sleep(times[2 ] * 1000 );
- System.out.println(now() + tourName + ” Reached Shaoguan”);
- barrier.await();
- Thread.sleep(times[3 ] * 1000 );
- System.out.println(now() + tourName + ” Reached Changsha”);
- barrier.await();
- Thread.sleep(times[4 ] * 1000 );
- System.out.println(now() + tourName + ” Reached Wuhan”);
- barrier.await();
- } catch (InterruptedException e) {
- } catch (BrokenBarrierException e) {
- }
- }
- }
-
- public static void main(String[] args) {
-
- CyclicBarrier barrier = new CyclicBarrier( 3 );
- ExecutorService exec = Executors.newFixedThreadPool(3 );
- exec.submit(new Tour(barrier, “WalkTour”, timeWalk));
- exec.submit(new Tour(barrier, “SelfTour”, timeSelf));
- exec.submit(new Tour(barrier, “BusTour”, timeBus));
- exec.shutdown();
- }
- }
运行结果:
00:02:25: SelfTour Reached Shenzhen
00:02:25: BusTour Reached Shenzhen
00:02:27: WalkTour Reached Shenzhen
00:02:30: SelfTour Reached Guangzhou
00:02:31: BusTour Reached Guangzhou
00:02:35: WalkTour Reached Guangzhou
00:02:39: SelfTour Reached Shaoguan
00:02:41: BusTour Reached Shaoguan
并发库中的BlockingQueue是一个比较好玩的类,顾名思义,就是阻塞队列。该类主要提供了两个方法put()和take(),前者将一 个对象放到队列中,若是队列已经满了,就等待直到有空闲节点;后者从head取一个对象,若是没有对象,就等待直到有可取的对象。
下面的例子比较简单,一个读线程,用于将要处理的文件对象添加到阻塞队列中,另外四个写线程用于取出文件对象,为了模拟写操做耗时长的特色,特让 线程睡眠一段随机长度的时间。另外,该Demo也使用到了线程池和原子整型(AtomicInteger),AtomicInteger能够在并发状况下 达到原子化更新,避免使用了synchronized,并且性能很是高。因为阻塞队列的put和take操做会阻塞,为了使线程退出,特在队列中添加了一 个“标识”,算法中也叫“哨兵”,当发现这个哨兵后,写线程就退出。
固然线程池也要显式退出了。数据库
- package concurrent;
- import java.io.File;
- import java.io.FileFilter;
- import java.util.concurrent.BlockingQueue;
- import java.util.concurrent.ExecutorService;
- import java.util.concurrent.Executors;
- import java.util.concurrent.LinkedBlockingQueue;
- import java.util.concurrent.atomic.AtomicInteger;
-
- public class TestBlockingQueue {
- static long randomTime() {
- return ( long ) (Math.random() * 1000 );
- }
-
- public static void main(String[] args) {
-
- final BlockingQueue queue = new LinkedBlockingQueue( 100 );
-
- final ExecutorService exec = Executors.newFixedThreadPool( 5 );
- final File root = new File(“F:\\JavaLib”);
-
- final File exitFile = new File(“”);
-
- final AtomicInteger rc = new AtomicInteger();
-
- final AtomicInteger wc = new AtomicInteger();
-
- Runnable read = new Runnable() {
- public void run() {
- scanFile(root);
- scanFile(exitFile);
- }
-
- public void scanFile(File file) {
- if (file.isDirectory()) {
- File[] files = file.listFiles(new FileFilter() {
- public boolean accept(File pathname) {
- return pathname.isDirectory()
- || pathname.getPath().endsWith(“.java”);
- }
- });
- for (File one : files)
- scanFile(one);
- } else {
- try {
- int index = rc.incrementAndGet();
- System.out.println(“Read0: ” + index + ” “
- + file.getPath());
- queue.put(file);
- } catch (InterruptedException e) {
- }
- }
- }
- };
- exec.submit(read);
-
- for ( int index = 0 ; index < 4 ; index++) {
-
- final int NO = index;
- Runnable write = new Runnable() {
- String threadName = “Write” + NO;
- public void run() {
- while ( true ) {
- try {
- Thread.sleep(randomTime());
- int index = wc.incrementAndGet();
- File file = queue.take();
-
- if (file == exitFile) {
-
- queue.put(exitFile);
- break ;
- }
- System.out.println(threadName + “: ” + index + ” “
- + file.getPath());
- } catch (InterruptedException e) {
- }
- }
- }
- };
- exec.submit(write);
- }
- exec.shutdown();
- }
- }
从名字能够看出,CountDownLatch是一个倒数计数的锁,当倒数到0时触发事件,也就是开锁,其余人就能够进入了。在一些应用场合中,须要等待某个条件达到要求后才能作后面的事情;同时当线程都完成后也会触发事件,以便进行后面的操做。
CountDownLatch最重要的方法是countDown()和await(),前者主要是倒数一次,后者是等待倒数到0,若是没有到达0,就只有阻塞等待了。
一个CountDouwnLatch实例是不能重复使用的,也就是说它是一次性的,锁一经被打开就不能再关闭使用了,若是想重复使用,请考虑使用CyclicBarrier。
下面的例子简单的说明了CountDownLatch的使用方法,模拟了100米赛跑,10名选手已经准备就绪,只等裁判一声令下。当全部人都到达终点时,比赛结束。
一样,线程池须要显式shutdown。浏览器
- package concurrent;
-
- import java.util.concurrent.CountDownLatch;
- import java.util.concurrent.ExecutorService;
- import java.util.concurrent.Executors;
-
- public class TestCountDownLatch {
- public static void main(String[] args) throws InterruptedException {
-
- final CountDownLatch begin = new CountDownLatch( 1 );
-
- final CountDownLatch end = new CountDownLatch( 10 );
-
- final ExecutorService exec = Executors.newFixedThreadPool( 10 );
- for ( int index = 0 ; index < 10 ; index++) {
- final int NO = index + 1 ;
- Runnable run = new Runnable(){
- public void run() {
- try {
- begin.await();
- Thread.sleep((long ) (Math.random() * 10000 ));
- System.out.println(“No.” + NO + ” arrived”);
- } catch (InterruptedException e) {
- } finally {
- end.countDown();
- }
- }
- };
- exec.submit(run);
- }
- System.out.println(“Game Start”);
- begin.countDown();
- end.await();
- System.out.println(“Game Over”);
- exec.shutdown();
- }
- }
运行结果:
Game Start
No.4 arrived
No.1 arrived
No.7 arrived
No.9 arrived
No.3 arrived
No.2 arrived
No.8 arrived
No.10 arrived
No.6 arrived
No.5 arrived
Game Over
有时候在实际应用中,某些操做很耗时,但又不是不可或缺的步骤。好比用网页浏览器浏览新闻时,最重要的是要显示文字内容,至于与新闻相匹配的图片 就没有那么重要的,因此此时首先保证文字信息先显示,而图片信息会后显示,但又不能不显示,因为下载图片是一个耗时的操做,因此必须一开始就得下载。
Java的并发库的Future类就能够知足这个要求。Future的重要方法包括get()和cancel(),get()获取数据对象,若是 数据没有加载,就会阻塞直到取到数据,而 cancel()是取消数据加载。另一个get(timeout)操做,表示若是在timeout时间内没有取到就失败返回,而再也不阻塞。
下面的Demo简单的说明了Future的使用方法:一个很是耗时的操做必须一开始启动,但又不能一直等待;其余重要的事情又必须作,等完成后,就能够作不重要的事情。服务器
- package concurrent;
-
- import java.util.concurrent.Callable;
- import java.util.concurrent.ExecutionException;
- import java.util.concurrent.ExecutorService;
- import java.util.concurrent.Executors;
- import java.util.concurrent.Future;
-
- public class TestFutureTask {
- public static void main(String[] args) throws InterruptedException,
- ExecutionException {
- final ExecutorService exec = Executors.newFixedThreadPool( 5 );
- Callable call = new Callable() {
- public String call() throws Exception {
- Thread.sleep(1000 * 5 );
- return “Other less important but longtime things.”;
- }
- };
- Future task = exec.submit(call);
-
- Thread.sleep(1000 * 3 );
- System.out.println(“Let’s do important things.”);
-
- String obj = task.get();
- System.out.println(obj);
-
- exec.shutdown();
- }
- }
运行结果:
Let’s do important things.
Other less important but longtime things.
考虑如下场景:浏览网页时,浏览器了5个线程下载网页中的图片文件,因为图片大小、网站访问速度等诸多因素的影响,完成图片下载的时间就会有很大的不一样。若是先下载完成的图片就会被先显示到界面上,反之,后下载的图片就后显示。
Java的并发库的CompletionService能够知足这种场景要求。该接口有两个重要方法:submit()和take()。 submit用于提交一个runnable或者callable,通常会提交给一个线程池处理;而take就是取出已经执行完毕runnable或者 callable实例的Future对象,若是没有知足要求的,就等待了。 CompletionService还有一个对应的方法poll,该方法与take相似,只是不会等待,若是没有知足要求,就返回null对象。网络
- package concurrent;
-
- import java.util.concurrent.Callable;
- import java.util.concurrent.CompletionService;
- import java.util.concurrent.ExecutionException;
- import java.util.concurrent.ExecutorCompletionService;
- import java.util.concurrent.ExecutorService;
- import java.util.concurrent.Executors;
- import java.util.concurrent.Future;
-
- public class TestCompletionService {
- public static void main(String[] args) throws InterruptedException,
- ExecutionException {
- ExecutorService exec = Executors.newFixedThreadPool(10 );
- CompletionService serv =
- new ExecutorCompletionService(exec);
-
- for ( int index = 0 ; index < 5 ; index++) {
- final int NO = index;
- Callable downImg = new Callable() {
- public String call() throws Exception {
- Thread.sleep((long ) (Math.random() * 10000 ));
- return “Downloaded Image ” + NO;
- }
- };
- serv.submit(downImg);
- }
-
- Thread.sleep(1000 * 2 );
- System.out.println(“Show web content”);
- for ( int index = 0 ; index < 5 ; index++) {
- Future task = serv.take();
- String img = task.get();
- System.out.println(img);
- }
- System.out.println(“End”);
-
- exec.shutdown();
- }
- }
运行结果:
Show web content
Downloaded Image 1
Downloaded Image 2
Downloaded Image 4
Downloaded Image 0
Downloaded Image 3
End
操做系统的信号量是个很重要的概念,在进程控制方面都有应用。Java并发库的Semaphore能够很轻松完成信号量控制,Semaphore 能够控制某个资源可被同时访问的个数,acquire()获取一个许可,若是没有就等待,而release()释放一个许可。好比在Windows下能够 设置共享文件的最大客户端访问个数。
Semaphore维护了当前访问的个数,提供同步机制,控制同时访问的个数。在数据结构中链表能够保存“无限”的节点,用Semaphore能够实现有限大小的链表。另外重入锁ReentrantLock也能够实现该功能,但实现上要负责些,代码也要复杂些。
下面的Demo中申明了一个只有5个许可的Semaphore,而有20个线程要访问这个资源,经过acquire()和release()获取和释放访问许可。数据结构
- package concurrent;
-
- import java.util.concurrent.ExecutorService;
- import java.util.concurrent.Executors;
- import java.util.concurrent.Semaphore;
-
- public class TestSemaphore {
- public static void main(String[] args) {
-
- ExecutorService exec = Executors.newCachedThreadPool();
-
- final Semaphore semp = new Semaphore( 5 );
-
- for ( int index = 0 ; index < 20 ; index++) {
- final int NO = index;
- Runnable run = new Runnable() {
- public void run() {
- try {
-
- semp.acquire();
- System.out.println(“Accessing: ” + NO);
- Thread.sleep((long ) (Math.random() * 10000 ));
-
- semp.release();
- } catch (InterruptedException e) {
- }
- }
- };
- exec.execute(run);
- }
-
- exec.shutdown();
- }
- }
运行结果:
Accessing: 0
Accessing: 1
Accessing: 2
Accessing: 3
Accessing: 4
Accessing: 5
Accessing: 6
Accessing: 7
Accessing: 8
Accessing: 9
Accessing: 10
Accessing: 11
Accessing: 12
Accessing: 13
Accessing: 14
Accessing: 15
Accessing: 16
Accessing: 17
Accessing: 18
Accessing: 19 并发
已有 0 人发表留言,猛击->>这里<<-参与讨论
JavaEye推荐