Java并发框架(Concurrency)

Java并发框架java.util.concurrent是JDK5中引入到标准库中的(采用的是Doug Lea的并发库)。该包下的类可以分为这么块: 
Executors 
1)接口: 
Executor(例子涉及):用来执行提交的Runnable任务的对象。是一个简单的标准化接口,用来定义包括线程池、异步IO、轻量级任务框架等等。任务可以由一个新创建的线程、一个已有任务执行线程、或是线程直接调用execute()来执行,可以串行也可并行执行,取决于使用的是哪个Executor具体类。 
ExecutorService(例子涉及):Executor的子接口,提供了一个更加具体的异步任务执行框架:提供了管理结束的方法,以及能够产生Future以跟踪异步任务进程的方法。一个ExcutorService管理着任务队列和任务调度。 
ScheduledExecutorService(例子涉及):ExecutorService的子接口,增加了对延迟和定期任务执行的支持。 
Callable(例子涉及):一个返回结果或抛出异常的任务,实现类需要实现其中一个没有参数的叫做call的方法。Callabe类似于Runnable,但是Runnable不返回结果且不能抛出checked exception。ExecutorService提供了安排Callable异步执行的方法。 
Future(例子涉及):代表一个异步计算的结果(由于是并发执行,结果可以在一段时间后才计算完成,其名字可能也就是代表这个意思吧),提供了可判断执行是否完成以及取消执行的方法。 

2)实现: 
ThreadPoolExecutor和ScheduledThreadPoolExecutor:可配置线程池(后者具备延迟或定期调度功能)。 
Executors(例子涉及):提供Executor、ExecutorService、ScheduledExecutorService、ThreadFactory以及Callable的工厂方法及工具方法。 
FutureTask:对Future的实现 
ExecutorCompletionService(例子涉及):帮助协调若干(成组)异步任务的处理。 


Queues 
非阻塞队列:ConcurrentLinkedQueue类提供了一个高效可伸缩线程安全非阻塞FIFO队列。 
阻塞队列:BlockingQueue接口,有五个实现类:LinkedBlockingQueue(例子涉及)、ArrayBlockingQueue、SynchronousQueue、PriorityBlockingQueue和DelayQueue。他们对应了不同的应用环境:生产者/消费者、消息发送、并发任务、以及相关并发设计。 


Timing 
TimeUnit类(例子涉及):提供了多种时间粒度(包括纳秒)用以表述和控制基于超时的操作。 


Synchronizers 提供特定用途同步语境 
Semaphore(例子涉及):计数信号量,这是一种经典的并发工具。 
CountDownLatch(例子涉及):简单的倒计数同步工具,可以让一个或多个线程等待直到另外一些线程中的一组操作处理完成。 
CyclicBarrier(例子涉及):可重置的多路同步工具,可重复使用(CountDownLatch是不能重复使用的)。 
Exchanger:允许两个线程在汇合点交换对象,在一些pipeline设计中非常有用。 


Concurrent Collections 
除队列外,该包还提供了一些为多线程上下文设计的集合实现:ConcurrentHashMap、CopyOnWriteArrayList及CopyOnWriteArraySet。 

注意:"Concurrent"前缀的类有别于"synchronized"前缀的类。“concurrent”集合是线程安全的,不需要由单排斥锁控制的(无锁的)。以ConcurrentHashMap为例,允许任何数量的并发读及可调数量的并发写。“Synchronized”类则一般通过一个单锁来防止对集合的所有访问,开销大且伸缩性差。(关于无锁并发算法的一些讨论,可以参见本站点《Groovy++里的快速不可变持久函数式队列》、《Groovy++里的无锁消息传递算法》、《Groovy++里的agents》等相关文章) 

例子 
上面基本上是官方概念性的描述,要想快速掌握,还是多看些例子比较好。抓虾上面就有一篇非常不错的相关文章(JavaEye上也有人转载),里面搜集的例子都比较浅显易懂,很适合学习Java并发框架用。严重推荐! 

java.util.conrurrent下还有两个子包多少也可能会用到: 

java.util.concurrent.atomic包下是一组工具类,支持在单个变量上无锁线程安全编程。 

java.util.concurrent.locks包提供了一个用于锁定和等待条件的框架、不同于内建同步和监视器(synchronization and monitors)。 
..
 




原文: http://daoger.iteye.com/blog/142485  

JDK5中的一个亮点就是将Doug Lea的并发库引入到Java标准库中。Doug Lea确实是一个牛人,能教书,能出书,能编码,不过这在国外还是比较普遍的,而国内的教授们就相差太远了。 

一般的服务器都需要线程池,比如Web、FTP等服务器,不过它们一般都自己实现了线程池,比如以前介绍过的Tomcat、Resin和Jetty等,现在有了JDK5,我们就没有必要重复造车轮了,直接使用就可以,何况使用也很方便,性能也非常高。 


Java代码   收藏代码
  1. package concurrent;  
  2.   
  3. import java.util.concurrent.ExecutorService;  
  4. import java.util.concurrent.Executors;  
  5.   
  6. public class TestThreadPool {  
  7.     public static void main(String args[]) throws InterruptedException {  
  8.     // only two threads  
  9.     ExecutorService exec = Executors.newFixedThreadPool(2);  
  10.     for (int index = 0; index < 100; index++) {  
  11.         Runnable run = new Runnable() {  
  12.         public void run() {  
  13.             long time = (long) (Math.random() * 1000);  
  14.             System.out.println("Sleeping " + time + "ms");  
  15.             try {  
  16.             Thread.sleep(time);  
  17.             } catch (InterruptedException e) {  
  18.             }  
  19.         }  
  20.         };  
  21.         exec.execute(run);  
  22.     }  
  23.     // must shutdown  
  24.     exec.shutdown();  
  25.     }  
  26. }  


上面是一个简单的例子,使用了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可以轻松的完成这些任务,而且非常的简单。 


Java代码   收藏代码
  1. package concurrent;     
  2. import static java.util.concurrent.TimeUnit.SECONDS;     
  3. import java.util.Date;     
  4. import java.util.concurrent.Executors;     
  5. import java.util.concurrent.ScheduledExecutorService;     
  6. import java.util.concurrent.ScheduledFuture;     
  7.   
  8. public class TestScheduledThread {     
  9.     @SuppressWarnings("unchecked")  
  10.     public static void main(String[] args) {     
  11.     final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(2);     
  12.     final Runnable beeper = new Runnable() {     
  13.         int count = 0;  
  14.         public void run() {  
  15.             System.out.println(new Date() + " beep " + (++count));     
  16.         }     
  17.     };  
  18.       
  19.     // 1秒钟后运行,并每隔2秒运行一次     
  20.     final ScheduledFuture beeperHandle = scheduler.scheduleAtFixedRate(beeper, 12, SECONDS);  
  21.       
  22.     // 2秒钟后运行,并每次在上次任务运行完后等待5秒后重新运行     
  23.     final ScheduledFuture beeperHandle2 = scheduler.scheduleWithFixedDelay(beeper, 25, SECONDS);  
  24.       
  25.     // 30秒后结束关闭任务,并且关闭Scheduler     
  26.     scheduler.schedule(new Runnable() {  
  27.         public void run() {  
  28.             beeperHandle.cancel(true);     
  29.             beeperHandle2.cancel(true);     
  30.             scheduler.shutdown();     
  31.         }  
  32.     }, 30, SECONDS);     
  33.     }     
  34. }   

为了退出进程,上面的代码中加入了关闭Scheduler的操作。而对于24小时运行的应用而言,是没有必要关闭Scheduler的。 

在实际应用中,有时候需要多个线程同时工作以完成同一件事情,而且在完成过程中,往往会等待其他线程都完成某一阶段后再执行,等所有线程都到达某一个阶段后再统一执行。 

比如有几个旅行团需要途经深圳、广州、韶关、长沙最后到达武汉。旅行团中有自驾游的,有徒步的,有乘坐旅游大巴的;这些旅行团同时出发,并且每到一个目的地,都要等待其他旅行团到达此地后再同时出发,直到都到达终点站武汉。 

这时候CyclicBarrier就可以派上用场。CyclicBarrier最重要的属性就是参与者个数,另外最要方法是await()。当所有线程都调用了await()后,就表示这些线程都可以继续执行,否则就会等待。 


Java代码   收藏代码
  1. package concurrent;  
  2.   
  3. import java.text.SimpleDateFormat;  
  4. import java.util.Date;  
  5. import java.util.concurrent.BrokenBarrierException;  
  6. import java.util.concurrent.CyclicBarrier;  
  7. import java.util.concurrent.ExecutorService;  
  8. import java.util.concurrent.Executors;  
  9.   
  10. public class TestCyclicBarrier {  
  11.     // 徒步需要的时间: Shenzhen, Guangzhou, Shaoguan, Changsha, Wuhan  
  12.     private static int[] timeWalk = { 58151510 };  
  13.     // 自驾游  
  14.     private static int[] timeSelf = { 13445 };  
  15.     // 旅游大巴  
  16.     private static int[] timeBus = { 24667 };  
  17.   
  18.     static String now() {  
  19.     SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");  
  20.     return sdf.format(new Date()) + ": ";  
  21.     }  
  22.   
  23.     static class Tour implements Runnable {  
  24.     private int[] times;  
  25.     private CyclicBarrier barrier;  
  26.     private String tourName;  
  27.   
  28.     public Tour(CyclicBarrier barrier, String tourName, int[] times) {  
  29.         this.times = times;  
  30.         this.tourName = tourName;  
  31.         this.barrier = barrier;  
  32.     }  
  33.   
  34.     public void run() {  
  35.         try {  
  36.         Thread.sleep(times[0] * 1000);  
  37.         System.out.println(now() + tourName + " Reached Shenzhen");  
  38.         barrier.await();  
  39.         Thread.sleep(times[1] * 1000);  
  40.         System.out.println(now() + tourName + " Reached Guangzhou");  
  41.         barrier.await();  
  42.         Thread.sleep(times[2] * 1000);  
  43.         System.out.println(now() + tourName + " Reached Shaoguan");  
  44.         barrier.await();  
  45.         Thread.sleep(times[3] * 1000);  
  46.         System.out.println(now() + tourName + " Reached Changsha");  
  47.         barrier.await();  
  48.         Thread.sleep(times[4] * 1000);  
  49.         System.out.println(now() + tourName + " Reached Wuhan");  
  50.         barrier.await();  
  51.         } catch (InterruptedException e) {  
  52.         } catch (BrokenBarrierException e) {  
  53.         }  
  54.     }  
  55.     }  
  56.   
  57.     public static void main(String[] args) {  
  58.     // 三个旅行团  
  59.     CyclicBarrier barrier = new CyclicBarrier(3);  
  60.     ExecutorService exec = Executors.newFixedThreadPool(3);  
  61.     exec.submit(new Tour(barrier, "WalkTour", timeWalk));  
  62.     exec.submit(new Tour(barrier, "SelfTour", timeSelf));  
  63.     exec.submit(new Tour(barrier, "BusTour", timeBus));  
  64.     exec.shutdown();  
  65.     }  
  66. }  



运行结果: 
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操作会阻塞,为了使线程退出,特在队列中添加了一个“标识”,算法中也叫“哨兵”,当发现这个哨兵后,写线程就退出。 

当然线程池也要显式退出了。 


Java代码   收藏代码
  1. package concurrent;  
  2.   
  3. import java.io.File;  
  4. import java.io.FileFilter;  
  5. import java.util.concurrent.BlockingQueue;  
  6. import java.util.concurrent.ExecutorService;  
  7. import java.util.concurrent.Executors;  
  8. import java.util.concurrent.LinkedBlockingQueue;  
  9. import java.util.concurrent.atomic.AtomicInteger;  
  10.   
  11. public class TestBlockingQueue {  
  12.     static long randomTime() {  
  13.     return (long) (Math.random() * 1000);  
  14.     }  
  15.   
  16.     @SuppressWarnings("unchecked")  
  17.     public static void main(String[] args) {  
  18.     // 能容纳100个文件  
  19.     final BlockingQueue queue = new LinkedBlockingQueue(100);  
  20.     // 线程池  
  21.     final ExecutorService exec = Executors.newFixedThreadPool(5);  
  22.     final File root = new File("F:\\JavaLib");  
  23.     // 完成标志  
  24.     final File exitFile = new File("");  
  25.     // 读个数  
  26.     final AtomicInteger rc = new AtomicInteger();  
  27.     // 写个数  
  28.     final AtomicInteger wc = new AtomicInteger();  
  29.     // 读线程  
  30.     Runnable read = new Runnable() {  
  31.         public void run() {  
  32.         scanFile(root);  
  33.         scanFile(exitFile);  
  34.         }  
  35.   
  36.         public void scanFile(File file) {  
  37.         if (file.isDirectory()) {  
  38.             File[] files = file.listFiles(new FileFilter() {  
  39.             public boolean accept(File pathname) {  
  40.                 return pathname.isDirectory() || pathname.getPath().endsWith(".java");  
  41.             }  
  42.             });  
  43.             for (File one : files)  
  44.             scanFile(one);  
  45.         } else {  
  46.             try {  
  47.             int index = rc.incrementAndGet();  
  48.             System.out.println("Read0: " + index + " " + file.getPath());  
  49.             queue.put(file);  
  50.             } catch (InterruptedException e) {  
  51.             }  
  52.         }  
  53.         }  
  54.     };  
  55.     exec.submit(read);  
  56.     // 四个写线程  
  57.     for (int index = 0; index < 4; index++) {  
  58.         // write thread  
  59.         final int NO = index;  
  60.         Runnable write = new Runnable() {  
  61.         String threadName = "Write" + NO;  
  62.   
  63.         public void run() {  
  64.             while (true) {  
  65.             try {  
  66.                 Thread.sleep(randomTime());  
  67.                 int index = wc.incrementAndGet();  
  68.                 File file = (File) queue.take();  
  69.                 // 队列已经无对象  
  70.                 if (file == exitFile) {  
  71.                 // 再次添加"标志",以让其他线程正常退出  
  72.                 queue.put(exitFile);  
  73.                 break;  
  74.                 }  
  75.                 System.out.println(threadName + ": " + index + " " + file.getPath());  
  76.             } catch (InterruptedException e) {  
  77.             }  
  78.             }  
  79.         }  
  80.         };  
  81.         exec.submit(write);  
  82.     }  
  83.     exec.shutdown();  
  84.     }  
  85. }  



从名字可以看出,CountDownLatch是一个倒数计数的锁,当倒数到0时触发事件,也就是开锁,其他人就可以进入了。在一些应用场合中,需要等待某个条件达到要求后才能做后面的事情;同时当线程都完成后也会触发事件,以便进行后面的操作。 


CountDownLatch最重要的方法是countDown()和await(),前者主要是倒数一次,后者是等待倒数到0,如果没有到达0,就只有阻塞等待了。 

一个CountDouwnLatch实例是不能重复使用的,也就是说它是一次性的,锁一经被打开就不能再关闭使用了,如果想重复使用,请考虑使用CyclicBarrier。 

下面的例子简单的说明了CountDownLatch的使用方法,模拟了100米赛跑,10名选手已经准备就绪,只等裁判一声令下。当所有人都到达终点时,比赛结束。 

同样,线程池需要显式shutdown。 


Java代码   收藏代码
  1. package concurrent;  
  2.   
  3. import java.util.concurrent.CountDownLatch;  
  4. import java.util.concurrent.ExecutorService;  
  5. import java.util.concurrent.Executors;  
  6.   
  7. public class TestCountDownLatch {  
  8.     public static void main(String[] args) throws InterruptedException {  
  9.     // 开始的倒数锁  
  10.     final CountDownLatch begin = new CountDownLatch(1);  
  11.     // 结束的倒数锁  
  12.     final CountDownLatch end = new CountDownLatch(10);  
  13.     // 十名选手  
  14.     final ExecutorService exec = Executors.newFixedThreadPool(10);  
  15.     for (int index = 0; index < 10; index++) {  
  16.         final int NO = index + 1;  
  17.         Runnable run = new Runnable() {  
  18.         public void run() {  
  19.             try {  
  20.             begin.await();  
  21.             Thread.sleep((long) (Math.random() * 10000));  
  22.             System.out.println("No." + NO + " arrived");  
  23.             } catch (InterruptedException e) {  
  24.             } finally {  
  25.             end.countDown();  
  26.             }  
  27.         }  
  28.         };  
  29.         exec.submit(run);  
  30.     }  
  31.     System.out.println("Game Start");  
  32.     begin.countDown();  
  33.     end.await();  
  34.     System.out.println("Game Over");  
  35.     exec.shutdown();  
  36.     }  
  37. }  


运行结果: 
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的使用方法:一个非常耗时的操作必须一开始启动,但又不能一直等待;其他重要的事情又必须做,等完成后,就可以做不重要的事情。 

  
Java代码   收藏代码
  1. package concurrent;  
  2.   
  3. import java.util.concurrent.Callable;  
  4. import java.util.concurrent.ExecutionException;  
  5. import java.util.concurrent.ExecutorService;  
  6. import java.util.concurrent.Executors;  
  7. import java.util.concurrent.Future;  
  8.   
  9. public class TestFutureTask {  
  10.     @SuppressWarnings("unchecked")  
  11.     public static void main(String[] args) throws InterruptedException, ExecutionException {  
  12.     final ExecutorService exec = Executors.newFixedThreadPool(5);  
  13.     Callable call = new Callable() {  
  14.         public String call() throws Exception {  
  15.         Thread.sleep(1000 * 5);  
  16.         return "Other less important but longtime things.";  
  17.         }  
  18.     };  
  19.     Future task = exec.submit(call);  
  20.     // 重要的事情  
  21.     Thread.sleep(1000 * 3);  
  22.     System.out.println("Let’s do important things.");  
  23.     // 其他不重要的事情  
  24.     String obj = (String) task.get();  
  25.     System.out.println(obj);  
  26.     // 关闭线程池  
  27.     exec.shutdown();  
  28.     }  
  29. }  


运行结果: 
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对象。 


Java代码   收藏代码
  1. package concurrent;  
  2.   
  3. import java.util.concurrent.Callable;  
  4. import java.util.concurrent.CompletionService;  
  5. import java.util.concurrent.ExecutionException;  
  6. import java.util.concurrent.ExecutorCompletionService;  
  7. import java.util.concurrent.ExecutorService;  
  8. import java.util.concurrent.Executors;  
  9. import java.util.concurrent.Future;  
  10.   
  11. public class TestCompletionService {  
  12.     @SuppressWarnings("unchecked")  
  13.     public static void main(String[] args) throws InterruptedException, ExecutionException {  
  14.     ExecutorService exec = Executors.newFixedThreadPool(10);  
  15.     CompletionService serv = new ExecutorCompletionService(exec);  
  16.   
  17.     for (int index = 0; index < 5; index++) {  
  18.         final int NO = index;  
  19.         Callable downImg = new Callable() {  
  20.         public String call() throws Exception {  
  21.             Thread.sleep((long) (Math.random() * 10000));  
  22.             return "Downloaded Image " + NO;  
  23.         }  
  24.         };  
  25.         serv.submit(downImg);  
  26.     }  
  27.   
  28.     Thread.sleep(1000 * 2);  
  29.     System.out.println("Show web content");  
  30.     for (int index = 0; index < 5; index++) {  
  31.         Future task = serv.take();  
  32.         String img = (String) task.get();  
  33.         System.out.println(img);  
  34.     }  
  35.     System.out.println("End");  
  36.     // 关闭线程池  
  37.     exec.shutdown();  
  38.     }  
  39. }  


运行结果: 
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()获取和释放访问许可。 


Java代码   收藏代码
  1. package concurrent;  
  2.   
  3. import java.util.concurrent.ExecutorService;  
  4. import java.util.concurrent.Executors;  
  5. import java.util.concurrent.Semaphore;  
  6.   
  7. public class TestSemaphore {  
  8.     public static void main(String[] args) {  
  9.     // 线程池  
  10.     ExecutorService exec = Executors.newCachedThreadPool();  
  11.     // 只能5个线程同时访问  
  12.     final Semaphore semp = new Semaphore(5);  
  13.     // 模拟20个客户端访问  
  14.     for (int index = 0; index < 20; index++) {  
  15.         final int NO = index;  
  16.         Runnable run = new Runnable() {  
  17.         public void run() {  
  18.             try {  
  19.             // 获取许可  
  20.             semp.acquire();  
  21.             System.out.println("Accessing: " + NO);  
  22.             Thread.sleep((long) (Math.random() * 10000));  
  23.             // 访问完后,释放  
  24.             semp.release();  
  25.             } catch (InterruptedException e) {  
  26.             }  
  27.         }  
  28.         };  
  29.         exec.execute(run);  
  30.     }  
  31.     // 退出线程池  
  32.     exec.shutdown();  
  33.     }  
  34. }  


运行结果: 
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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值