from:http://www.java2000.net/p13007
Count是一个多线程偶数计数器,通常我们应该使用synchronized,或者Lock来保证该递增操作的原子性和可见性。本例使用了单例的ExecutorService,来保证Count的递增的原子性。
运行结果
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
Count是一个多线程偶数计数器,通常我们应该使用synchronized,或者Lock来保证该递增操作的原子性和可见性。本例使用了单例的ExecutorService,来保证Count的递增的原子性。
- import java.util.concurrent.Callable;
- import java.util.concurrent.ExecutionException;
- import java.util.concurrent.ExecutorService;
- import java.util.concurrent.Executors;
- /**
- * 通过ExecutorService实现单例的同步访问控制。
- *
- * @author 老紫竹 JAVA世纪网(java2000.net)
- *
- */
- public class T {
- private final ExecutorService exec = Executors.newSingleThreadExecutor();
- public long getCount() throws InterruptedException, ExecutionException {
- return exec.submit(new Callable<Long>() {
- @Override
- public Long call() throws Exception {
- return ++count;
- }
- }).get();
- }
- private long count;
- public void add() {
- exec.execute(new Runnable() {
- @Override
- public void run() {
- count++;
- System.out.println(count);
- }
- });
- }
- public static void main(String[] args) {
- final T t = new T();
- class TT extends Thread {
- public void run() {
- for (int i = 1; i <= 5; i++) {
- try {
- t.add();
- System.out.println(t.getCount());
- Thread.sleep(10);
- } catch (Exception e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
- }
- }
- for (int i = 1; i <= 5; i++) {
- new TT().start();
- }
- }
- }
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