通过ExecutorService实现单例的同步访问控制

from:http://www.java2000.net/p13007

Count是一个多线程偶数计数器,通常我们应该使用synchronized,或者Lock来保证该递增操作的原子性和可见性。本例使用了单例的ExecutorService,来保证Count的递增的原子性。

  1. import java.util.concurrent.Callable;
  2. import java.util.concurrent.ExecutionException;
  3. import java.util.concurrent.ExecutorService;
  4. import java.util.concurrent.Executors;
  5. /**
  6.  * 通过ExecutorService实现单例的同步访问控制。
  7.  * 
  8.  * @author 老紫竹 JAVA世纪网(java2000.net)
  9.  * 
  10.  */
  11. public class T {
  12.   private final ExecutorService exec = Executors.newSingleThreadExecutor();
  13.   public long getCount() throws InterruptedException, ExecutionException {
  14.     return exec.submit(new Callable<Long>() {
  15.       @Override
  16.       public Long call() throws Exception {
  17.         return ++count;
  18.       }
  19.     }).get();
  20.   }
  21.   private long count;
  22.   public void add() {
  23.     exec.execute(new Runnable() {
  24.       @Override
  25.       public void run() {
  26.         count++;
  27.         System.out.println(count);
  28.       }
  29.     });
  30.   }
  31.   public static void main(String[] args) {
  32.     final T t = new T();
  33.     class TT extends Thread {
  34.       public void run() {
  35.         for (int i = 1; i <= 5; i++) {
  36.           try {
  37.             t.add();
  38.             System.out.println(t.getCount());
  39.             Thread.sleep(10);
  40.           } catch (Exception e) {
  41.             // TODO Auto-generated catch block
  42.             e.printStackTrace();
  43.           }
  44.         }
  45.       }
  46.     }
  47.     for (int i = 1; i <= 5; i++) {
  48.       new TT().start();
  49.     }
  50.   }
  51. }
运行结果
1
2
3
4
5
6
7
10
8
9
11
12
15
16
19
14
17
20
13
18
21
22
24
26
28
25
29
27
30
23
31
32
35
37
39
33
36
38
34
40
41
42
45
47
49
43
44
46
48
50


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值