Skip to content

Commit a2bf8a4

Browse files
committed
Merge branch 'master' of https://github.com/Fadezed/concurrency
2 parents 6064d97 + b341f25 commit a2bf8a4

File tree

31 files changed

+1074
-38
lines changed

31 files changed

+1074
-38
lines changed

README.md

Lines changed: 19 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
1-
内容整理自[《Java并发编程实战》](https://time.geekbang.org/column/intro/159)
1+
内容整理自[《Java并发编程实战》](https://time.geekbang.org/column/intro/159)[《java-concurrency-patterns》](https://github.com/LeonardoZ/java-concurrency-patterns)
22
相关工具类[《vjtools》](https://github.com/vipshop/vjtools)
3-
WeChat:Zed-RD [![Build Status](https://travis-ci.org/Fadezed/concurrency.svg?branch=master)](https://travis-ci.org/Fadezed/concurrency)
3+
4+
[![Build Status](https://travis-ci.org/Fadezed/concurrency.svg?branch=master)](https://travis-ci.org/Fadezed/concurrency)
45

56

67
<div align="center">
@@ -39,20 +40,18 @@ WeChat:Zed-RD [![Build Status](https://travis-ci.org/Fadezed/concurrency.svg?br
3940

4041

4142
## 缓存导致的可见性问题
42-
4343
* 一个线程对共享变量的修改,另外一个线程能够立刻看到,我们称为**可见性**
44-
* [代码示例](https://github.com/Fadezed/concurrency/blob/master/src/main/java/com/example/concurrency/visibility/Visibility.java)
44+
* [代码示例](https://github.com/Fadezed/concurrency/blob/master/src/main/java/com/example/concurrency/features/visibility/Visibility.java)
4545
![单核CPU](media/15603316282468/a07e8182819e2b260ce85b2167d446da.png)
4646
![多核CPU](media/15603316282468/e2aa76928b2bc135e08e7590ca36e0ea.png)
4747

4848

4949
## 线程切换带来的原子性问题
5050
* 一个或者多个操作在 CPU 执行的过程中不被中断的特性称为**原子性**
51-
5251
* **时间片**概念
5352
* 线程切换 ---〉提升cpu利用率。 tips:Unix系统因支持多进程分时复用而出名。
54-
* 线程切换[代码示例](https://github.com/Fadezed/concurrency/blob/master/src/main/java/com/example/concurrency/contentSwitch/ContentSwitchTest.java)
55-
* 原子问题[代码示例](https://github.com/Fadezed/concurrency/blob/master/src/main/java/com/example/concurrency/atomic/AtomicCounter.java)
53+
* 线程切换[代码示例](https://github.com/Fadezed/concurrency/blob/master/src/main/java/com/example/concurrency/features/contentswitch/ContentSwitchTest.java)
54+
* 原子问题[代码示例](https://github.com/Fadezed/concurrency/blob/master/src/main/java/com/example/concurrency/features/atomic/AtomicCounter.java)
5655

5756
![254b129b145d80e9bb74123d6e620efb](media/15603316282468/254b129b145d80e9bb74123d6e620efb.png)
5857
* count+=1 操作分析
@@ -94,7 +93,7 @@ public class Singleton {
9493
## 按需禁用缓存以及编译优化 [代码来源](http://www.cs.umd.edu/~pugh/java/memoryModel/jsr-133-faq.html)
9594

9695
* ## volatile
97-
* [代码示例](https://github.com/Fadezed/concurrency/blob/master/src/main/java/com/example/concurrency/volatileExample/VolatileExample.java)
96+
* [代码示例](https://github.com/Fadezed/concurrency/blob/master/src/main/java/com/example/concurrency/features/volatilecase/VolatileExample.java)
9897

9998
* ## synchronized
10099

@@ -134,9 +133,9 @@ public class Singleton {
134133
* 偏向锁
135134
* 轻量级锁
136135
* 重量级锁
137-
138136
139-
* [代码示例](https://github.com/Fadezed/concurrency/blob/master/src/main/java/com/example/concurrency/synchronizedEx/SynchronizedExample.java)
137+
138+
* [代码示例](https://github.com/Fadezed/concurrency/blob/master/src/main/java/com/example/concurrency/features/synchronizedcase/SynchronizedExample.java)
140139
141140
```
142141
class X {
@@ -158,7 +157,7 @@ public class Singleton {
158157
159158
## final
160159
161-
* [代码示例](https://github.com/Fadezed/concurrency/blob/master/src/main/java/com/example/concurrency/finalEx/FinalExample.java)
160+
* [代码示例](https://github.com/Fadezed/concurrency/blob/master/src/main/java/com/example/concurrency/features/finalcase/FinalExample.java)
162161
* 修饰变量时,初衷是告诉编译器:这个变量生而不变,非immutable,即只能表示对象引用不能被赋值(例如List);
163162
* 修饰方法则方法不能被重写
164163
* 修饰类则不能被扩展继承。
@@ -238,7 +237,7 @@ public class Singleton {
238237
239238
-------
240239
# 4.JAVA线程的生命周期
241-
* [代码示例](https://github.com/Fadezed/concurrency/blob/master/src/main/java/com/example/concurrency/threadState/ThreadState.java)
240+
* [代码示例](https://github.com/Fadezed/concurrency/blob/master/src/main/java/com/example/concurrency/features/threadstate/ThreadState.java)
242241
243242
## 通用的线程生命周期
244243
* 初始状态
@@ -484,7 +483,7 @@ class Semaphore{
484483
### 使用方法
485484
#### 实现互斥
486485
#### 实现限流器(Semaphore 可以允许多个线程访问一个临界区)
487-
* [代码示例](https://github.com/Fadezed/concurrency/blob/master/src/main/java/com/example/concurrency/semaphore/SemaphoreEx.java)
486+
* [代码示例](https://github.com/Fadezed/concurrency/blob/master/src/main/java/com/example/concurrency/features/semaphore/SemaphoreEx.java)
488487
489488
490489
-------
@@ -495,16 +494,16 @@ class Semaphore{
495494
* 只允许一个线程写共享变量
496495
* 如果一个写线程正在执行写操作,此时禁止读线程读共享变量
497496
498-
* [代码示例](https://github.com/Fadezed/concurrency/blob/master/src/main/java/com/example/concurrency/readWriteLock/CacheByReadWriteLock.java)
497+
* [代码示例](https://github.com/Fadezed/concurrency/blob/master/src/main/java/com/example/concurrency/features/readwritelock/CacheByReadWriteLock.java)
499498
500499
## StampedLock 加上乐观读(无锁)
501-
* [代码示例](https://github.com/Fadezed/concurrency/blob/master/src/main/java/com/example/concurrency/readWriteLock/StampedLockEx.java)
500+
* [代码示例](https://github.com/Fadezed/concurrency/blob/master/src/main/java/com/example/concurrency/features/readwritelock/StampedLockEx.java)
502501
503502
## CountDownLatch
504-
* [代码示例](https://github.com/Fadezed/concurrency/blob/master/src/main/java/com/example/concurrency/countDownLatchEx/CountDownLatchEx.java)
503+
* [代码示例](https://github.com/Fadezed/concurrency/blob/master/src/main/java/com/example/concurrency/features/countdownlatch/CountDownLatchEx.java)
505504
506505
## CyclicBarrier
507-
* [代码示例](https://github.com/Fadezed/concurrency/blob/master/src/main/java/com/example/concurrency/cyclicBarrierEx/CyclicBarrierEx.java)
506+
* [代码示例](https://github.com/Fadezed/concurrency/blob/master/src/main/java/com/example/concurrency/features/cyclicbarrier/CyclicBarrierEx.java)
508507
509508
510509
@@ -581,7 +580,7 @@ CopyOnWriteArraySet、ConcurrentSkipListSet
581580
# 11. 原子类
582581
583582
* 无锁方案实现原理(Compare And Swap)
584-
* [代码示例](https://github.com/Fadezed/concurrency/blob/master/src/main/java/com/example/concurrency/atomic/SimulatedCAS.java)
583+
* [代码示例](https://github.com/Fadezed/concurrency/blob/master/src/main/java/com/example/concurrency/features/atomic/SimulatedCompareAndSwap.java)
585584
* 概览图
586585
![atomi](media/15608379390765/atomic.png)
587586
@@ -640,7 +639,7 @@ accumulateAndGet(x,func)
640639
* 而创建一个线程,却需要调用操作系统内核的 API,然后操作系统要为线程分配一系列的资源,这个成本就很高了。
641640
642641
## 线程池是一种生产者-消费者模式(非一般意义池化资源)
643-
* [代码示例](https://github.com/Fadezed/concurrency/blob/master/src/main/java/com/example/concurrency/threadPool/MyThreadPool.java)
642+
* [代码示例](https://github.com/Fadezed/concurrency/blob/master/src/main/java/com/example/concurrency/features/threadPool/MyThreadPool.java)
644643
* Java ThreadPoolExecutor
645644
646645
```
@@ -713,7 +712,7 @@ get(long timeout, TimeUnit unit);
713712
714713
715714
## FutureTask工具类(实现了RunnableFuture而它继承了Runnable和Future接口)
716-
* [代码示例](https://github.com/Fadezed/concurrency/blob/master/src/main/java/com/example/concurrency/futureTask/FutureTaskEx.java)
715+
* [代码示例](https://github.com/Fadezed/concurrency/blob/master/src/main/java/com/example/concurrency/features/futuretask/FutureTaskEx.java)
717716
* 构造函数类似线程池submit
718717
719718
```

src/main/java/com/example/concurrency/features/atomic/SimulatedCAS.java renamed to src/main/java/com/example/concurrency/features/atomic/SimulatedCompareAndSwap.java

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,12 +2,12 @@
22

33
/**
44
* 描述:
5-
* SimulatedCAS 模拟cas操作
5+
* SimulatedCompareAndSwap 模拟cas操作
66
*
77
* @author zed
88
* @since 2019-06-18 2:09 PM
99
*/
10-
public class SimulatedCAS{
10+
public class SimulatedCompareAndSwap {
1111
private int count;
1212

1313
/**
Lines changed: 116 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,116 @@
1+
package com.example.concurrency.features.completablefuture;
2+
3+
import com.example.concurrency.util.ThreadUtil;
4+
5+
import java.util.concurrent.CompletableFuture;
6+
import java.util.concurrent.TimeUnit;
7+
8+
/**
9+
* 描述:
10+
* CompletableFutureExample Java 8 异步编程可描述串行关系、AND汇聚关系和OR汇聚关系以及异常处理
11+
*
12+
* @author zed
13+
* @since 2019-07-03 1:57 PM
14+
*/
15+
public class CompletableFutureExample {
16+
/**
17+
* 任务 1:洗水壶 -> 烧开水
18+
*/
19+
private CompletableFuture<Void> f1 = CompletableFuture.runAsync(()->{
20+
System.out.println("T1: 洗水壶...");
21+
ThreadUtil.sleep(1, TimeUnit.SECONDS);
22+
System.out.println("T1: 烧开水...");
23+
ThreadUtil.sleep(15, TimeUnit.SECONDS);
24+
});
25+
/**
26+
* 任务 2:洗茶壶 -> 洗茶杯 -> 拿茶叶
27+
*/
28+
private CompletableFuture<String> f2 = CompletableFuture.supplyAsync(()->{
29+
System.out.println("T2: 洗茶壶...");
30+
ThreadUtil.sleep(1, TimeUnit.SECONDS);
31+
32+
System.out.println("T2: 洗茶杯...");
33+
ThreadUtil.sleep(2, TimeUnit.SECONDS);
34+
35+
System.out.println("T2: 拿茶叶...");
36+
ThreadUtil.sleep(1, TimeUnit.SECONDS);
37+
return " 龙井 ";
38+
});
39+
/**
40+
* 任务 3:任务 1 和任务 2 完成后执行:泡茶
41+
*/
42+
private CompletableFuture<String> f3 = f1.thenCombine(f2, (e, tf)->{
43+
System.out.println("T1: 拿到茶叶:" + tf);
44+
System.out.println("T1: 泡茶...");
45+
return " 上茶:" + tf;
46+
});
47+
48+
49+
public static void main(String[] args) {
50+
CompletableFutureExample example = new CompletableFutureExample();
51+
System.out.println(example.f3.join());
52+
}
53+
54+
/**
55+
* 描述串行关系 thenApply
56+
*/
57+
static class SerialRelation{
58+
private static CompletableFuture<String> f0 =
59+
CompletableFuture.supplyAsync(
60+
() -> "Hello World") //①
61+
.thenApply(s -> s + " QQ") //②
62+
.thenApply(String::toUpperCase);//③
63+
64+
public static void main(String[] args) {
65+
System.out.println(SerialRelation.f0.join());
66+
}
67+
}
68+
/**
69+
* 描述汇聚Or关系 thenApply
70+
*/
71+
static class ConvergeRelation{
72+
static CompletableFuture<String> f1 =
73+
CompletableFuture.supplyAsync(()->{
74+
int t = getRandom(5, 10);
75+
ThreadUtil.sleep(t, TimeUnit.SECONDS);
76+
return String.valueOf(t);
77+
});
78+
79+
static CompletableFuture<String> f2 =
80+
CompletableFuture.supplyAsync(()->{
81+
int t = getRandom(5, 10);
82+
ThreadUtil.sleep(t, TimeUnit.SECONDS);
83+
return String.valueOf(t);
84+
});
85+
86+
static CompletableFuture<String> f3 =
87+
f1.applyToEither(f2,s -> s);
88+
89+
90+
private static int getRandom(int i,int j){
91+
return (int) (Math.random() * (j - i)) +i;
92+
}
93+
public static void main(String[] args) {
94+
95+
System.out.println(ConvergeRelation.f3.join());
96+
}
97+
}
98+
99+
/**
100+
* 处理异常 此例为发生异常默认为0
101+
*/
102+
static class ExceptionHandler{
103+
private static CompletableFuture<Integer>
104+
f0 = CompletableFuture
105+
.supplyAsync(()->7/0)
106+
.thenApply(r->r*10)
107+
.exceptionally(e->0);
108+
109+
public static void main(String[] args) {
110+
System.out.println(ExceptionHandler.f0.join());
111+
}
112+
113+
}
114+
115+
}
116+
Lines changed: 72 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,72 @@
1+
package com.example.concurrency.features.completionservice;
2+
3+
import com.example.concurrency.features.threadPool.ThreadPoolBuilder;
4+
5+
import java.util.ArrayList;
6+
import java.util.List;
7+
import java.util.concurrent.*;
8+
9+
/**
10+
* 描述:
11+
* CompletionService BlockingQueue+Executor
12+
*
13+
* 批量执行异步任务 并且可以支持Forking Cluster模式即并行查询多个服务其中一个返回则结束
14+
* @author zed
15+
* @since 2019-07-03 10:07 AM
16+
*/
17+
public class ExecutorCompletionServiceExample {
18+
19+
private Integer exe()throws InterruptedException{
20+
// 创建线程池
21+
ThreadPoolExecutor pool = ThreadPoolBuilder.fixedPool().setPoolSize(3).build();
22+
// 创建 CompletionService
23+
CompletionService<Integer> completionService = new ExecutorCompletionService<>(pool);
24+
// 用于保存 Future 对象
25+
List<Future<Integer>> futures = new ArrayList<>(3);
26+
// 提交异步任务,并保存 future 到 futures
27+
futures.add(completionService.submit(this::getCoderByS1));
28+
futures.add(completionService.submit(this::getCoderByS2));
29+
futures.add(completionService.submit(this::getCoderByS3));
30+
// 获取最快返回的任务执行结果
31+
Integer r = 0;
32+
try {
33+
// 只要有一个成功返回,则 break 这里因为要判断是否是正确的结果 所以会循环三次,如果不考虑结果正确性,第一次拿出来的就是最先执行完的结果
34+
for (int i = 0; i < 3; ++i) {
35+
try {
36+
r = completionService.take().get();
37+
} catch (ExecutionException e) {
38+
e.printStackTrace();
39+
}
40+
// 简单地通过判空来检查是否成功返回
41+
if (r != null ) {
42+
break;
43+
}
44+
}
45+
} finally {
46+
// 取消所有任务
47+
for(Future<Integer> f : futures){
48+
f.cancel(true);
49+
50+
}
51+
}
52+
pool.shutdown();
53+
// 返回结果
54+
return r;
55+
56+
}
57+
private Integer getCoderByS1(){
58+
return null;
59+
}
60+
private Integer getCoderByS2(){
61+
return 2;
62+
}
63+
private Integer getCoderByS3(){
64+
return 3;
65+
}
66+
67+
public static void main(String[] args) throws InterruptedException{
68+
System.out.println(new ExecutorCompletionServiceExample().exe());
69+
}
70+
71+
}
72+

src/main/java/com/example/concurrency/features/concurrentHashMap/ConcurrentHashMapTest.java renamed to src/main/java/com/example/concurrency/features/concurrenthashmap/ConcurrentHashMapTest.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
package com.example.concurrency.features.concurrentHashMap;
1+
package com.example.concurrency.features.concurrenthashmap;
22

33
/**
44
* 描述:

src/main/java/com/example/concurrency/features/contentSwitch/ContentSwitchTest.java renamed to src/main/java/com/example/concurrency/features/contentswitch/ContentSwitchTest.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
package com.example.concurrency.features.contentSwitch;
1+
package com.example.concurrency.features.contentswitch;
22

33
import com.example.concurrency.features.threadPool.ThreadPoolBuilder;
44

src/main/java/com/example/concurrency/features/countDownLatchEx/CountDownLatchEx.java renamed to src/main/java/com/example/concurrency/features/countdownlatch/CountDownLatchEx.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
package com.example.concurrency.features.countDownLatchEx;
1+
package com.example.concurrency.features.countdownlatch;
22

33
import com.example.concurrency.features.threadPool.ThreadPoolBuilder;
44

src/main/java/com/example/concurrency/features/cyclicBarrierEx/CyclicBarrierEx.java renamed to src/main/java/com/example/concurrency/features/cyclicbarrier/CyclicBarrierEx.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
package com.example.concurrency.features.cyclicBarrierEx;
1+
package com.example.concurrency.features.cyclicbarrier;
22

33

44
import java.util.concurrent.CyclicBarrier;

src/main/java/com/example/concurrency/features/deadLock/DeadLockTest.java renamed to src/main/java/com/example/concurrency/features/deadlock/DeadLockTest.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
package com.example.concurrency.features.deadLock;
1+
package com.example.concurrency.features.deadlock;
22

33
import com.example.concurrency.features.threadPool.ThreadPoolBuilder;
44
import com.example.concurrency.util.ThreadDumpHelper;

0 commit comments

Comments
 (0)