Skip to content

Commit e2097ab

Browse files
committed
update 0303
1 parent 5762222 commit e2097ab

12 files changed

+385
-15
lines changed

03concurrency/0301/src/main/java/java0/conc0302/atomic/AtomicCount.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@ public class AtomicCount {
77

88
private AtomicInteger num = new AtomicInteger();
99

10-
public synchronized int add() {
10+
public int add() {
1111
return num.getAndIncrement();
1212
}
1313

03concurrency/0301/src/main/java/java0/conc0302/lock/ReentrantReadWriteLockDemo2.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -41,7 +41,7 @@ public Object readWrite(String key) {
4141

4242
public static void main(String[] args) {
4343
ReentrantReadWriteLockDemo2 demo2 = new ReentrantReadWriteLockDemo2();
44-
demo2.readWrite("wangwei");
44+
demo2.readWrite("bingfabiancheng");
4545
}
4646

4747
}
Lines changed: 81 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,81 @@
1+
package java0.conc0303.future;
2+
3+
import java.util.concurrent.CompletableFuture;
4+
5+
public class CompletableFutureDemo {
6+
7+
public static void main(String[] args){
8+
9+
// 1.变换结果
10+
System.out.println("=====>1.变换结果");
11+
String result1 = CompletableFuture.supplyAsync(()->{return "Hello ";}).thenApplyAsync(v -> v + "world").join();
12+
System.out.println(result1);
13+
14+
// 2.消费
15+
CompletableFuture.supplyAsync(()->{return "Hello ";}).thenAccept(v -> { System.out.println("=====>2.消费");System.out.println("consumer: " + v);});
16+
17+
// 3.组合
18+
System.out.println("=====>3.组合");
19+
String result3 = CompletableFuture.supplyAsync(()->{
20+
try {
21+
Thread.sleep(1000);
22+
} catch (InterruptedException e) {
23+
e.printStackTrace();
24+
}
25+
return "Hello";
26+
}).thenCombine(CompletableFuture.supplyAsync(()->{
27+
try {
28+
Thread.sleep(2000);
29+
} catch (InterruptedException e) {
30+
e.printStackTrace();
31+
}
32+
return "world";
33+
}),(s1,s2)->{return s1 + " " + s2;}).join();
34+
System.out.println("thenCombine:"+result3);
35+
36+
CompletableFuture.supplyAsync(() -> "Hello, java course.")
37+
.thenApply(String::toUpperCase).thenCompose(s -> CompletableFuture.supplyAsync(s::toLowerCase)).thenAccept(v -> { System.out.println("thenCompose:"+v);});
38+
39+
// 4.竞争
40+
System.out.println("=====>4.竞争");
41+
String result4 = CompletableFuture.supplyAsync(()->{
42+
try {
43+
Thread.sleep(100);
44+
} catch (InterruptedException e) {
45+
e.printStackTrace();
46+
}
47+
return "Hi Boy";
48+
}).applyToEither(CompletableFuture.supplyAsync(()->{
49+
try {
50+
Thread.sleep(300);
51+
} catch (InterruptedException e) {
52+
e.printStackTrace();
53+
}
54+
return "Hi Girl";
55+
}),(s)->{return s;}).join();
56+
System.out.println(result4);
57+
58+
// 5.补偿异常
59+
System.out.println("=====>5.补偿异常");
60+
String result5 = CompletableFuture.supplyAsync(()->{
61+
try {
62+
Thread.sleep(100);
63+
} catch (InterruptedException e) {
64+
e.printStackTrace();
65+
}
66+
if(true) {
67+
throw new RuntimeException("exception test!");
68+
}
69+
70+
return "Hi Boy";
71+
}).exceptionally(e->{
72+
System.out.println(e.getMessage());
73+
return "Hello world!";
74+
}).join();
75+
System.out.println(result5);
76+
77+
78+
79+
}
80+
81+
}
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
package java0.conc0303.future;
2+
3+
import java.util.Random;
4+
import java.util.concurrent.*;
5+
6+
public class FutureDemo1 {
7+
public static void main(String[] args) {
8+
ExecutorService executor = Executors.newCachedThreadPool();
9+
Future<Integer> result = executor.submit(new Callable<Integer>() {
10+
public Integer call() throws Exception {
11+
return new Random().nextInt();
12+
}
13+
});
14+
executor.shutdown();
15+
try {
16+
System.out.println("result:" + result.get());
17+
} catch (InterruptedException e) {
18+
e.printStackTrace();
19+
} catch (ExecutionException e) {
20+
e.printStackTrace();
21+
}
22+
}
23+
}
Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
package java0.conc0303.future;
2+
3+
import java.util.Random;
4+
import java.util.concurrent.*;
5+
6+
public class FutureTask1 {
7+
public static void main(String[] args) {
8+
//第一种方式
9+
FutureTask<Integer> task = new FutureTask<Integer>(new Callable<Integer>() {
10+
@Override
11+
public Integer call() throws Exception {
12+
return new Random().nextInt();
13+
}
14+
});
15+
new Thread(task).start();
16+
//第二种方方式
17+
// ExecutorService executor = Executors.newSingleThreadExecutor();
18+
// FutureTask<Integer> task = new FutureTask<Integer>(new Callable<Integer>() {
19+
// @Override
20+
// public Integer call() throws Exception {
21+
// return new Random().nextInt();
22+
// }
23+
// });
24+
// executor.submit(task);
25+
26+
try {
27+
System.out.println("result: " + task.get());
28+
} catch (InterruptedException e) {
29+
e.printStackTrace();
30+
} catch (ExecutionException e) {
31+
e.printStackTrace();
32+
}
33+
}
34+
35+
}
Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
package java0.conc0303.tool;
2+
3+
import java.util.concurrent.CountDownLatch;
4+
5+
public class CountDownLatchDemo {
6+
public static void main(String[] args) throws InterruptedException {
7+
CountDownLatch countDownLatch = new CountDownLatch(5);
8+
for(int i=0;i<5;i++){
9+
new Thread(new readNum(i,countDownLatch)).start();
10+
}
11+
countDownLatch.await(); // 注意跟CyclicBarrier不同,这里在主线程await
12+
System.out.println("==>各个子线程执行结束。。。。");
13+
System.out.println("==>主线程执行结束。。。。");
14+
}
15+
16+
static class readNum implements Runnable{
17+
private int id;
18+
private CountDownLatch latch;
19+
public readNum(int id,CountDownLatch latch){
20+
this.id = id;
21+
this.latch = latch;
22+
}
23+
@Override
24+
public void run() {
25+
synchronized (this){
26+
System.out.println("id:"+id+","+Thread.currentThread().getName());
27+
//latch.countDown();
28+
System.out.println("线程组任务"+id+"结束,其他任务继续");
29+
latch.countDown();
30+
}
31+
}
32+
}
33+
}
Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
package java0.conc0303.tool;
2+
3+
4+
import java.util.concurrent.CountDownLatch;
5+
import java.util.concurrent.ExecutorService;
6+
import java.util.concurrent.Executors;
7+
8+
public class CountDownLatchDemo2 {
9+
10+
private final static int threadCount = 200;
11+
12+
public static void main(String[] args) throws Exception {
13+
14+
ExecutorService exec = Executors.newCachedThreadPool();
15+
16+
final CountDownLatch countDownLatch = new CountDownLatch(threadCount);
17+
18+
for (int i = 0; i < threadCount; i++) {
19+
final int threadNum = i;
20+
exec.execute(() -> {
21+
try {
22+
test(threadNum);
23+
} catch (Exception e) {
24+
e.printStackTrace();
25+
} finally {
26+
countDownLatch.countDown();
27+
}
28+
});
29+
}
30+
countDownLatch.await();
31+
System.out.println("==>所有程序员完成任务,项目顺利上线!");
32+
exec.shutdown();
33+
}
34+
35+
private static void test(int threadNum) throws Exception {
36+
Thread.sleep(100);
37+
System.out.println(String.format("程序员[%d]完成任务。。。", threadNum));
38+
Thread.sleep(100);
39+
}
40+
}
Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
package java0.conc0303.tool;
2+
3+
import java.util.concurrent.CyclicBarrier;
4+
5+
public class CyclicBarrierDemo {
6+
public static void main(String[] args) throws InterruptedException {
7+
CyclicBarrier cyclicBarrier = new CyclicBarrier(5, new Runnable() {
8+
@Override
9+
public void run() {
10+
System.out.println("回调>>"+Thread.currentThread().getName());
11+
System.out.println("回调>>线程组执行结束");
12+
}
13+
});
14+
for (int i = 0; i < 5; i++) {
15+
new Thread(new readNum(i,cyclicBarrier)).start();
16+
}
17+
18+
System.out.println("==>各个子线程执行结束。。。。");
19+
System.out.println("==>主线程执行结束。。。。");
20+
21+
//CyclicBarrier 可以重复利用,
22+
// 这个是CountDownLatch做不到的
23+
// for (int i = 11; i < 16; i++) {
24+
// new Thread(new readNum(i,cyclicBarrier)).start();
25+
// }
26+
}
27+
static class readNum implements Runnable{
28+
private int id;
29+
private CyclicBarrier cyc;
30+
public readNum(int id,CyclicBarrier cyc){
31+
this.id = id;
32+
this.cyc = cyc;
33+
}
34+
@Override
35+
public void run() {
36+
synchronized (this){
37+
System.out.println("id:"+id+","+Thread.currentThread().getName());
38+
try {
39+
//cyc.await();
40+
System.out.println("线程组任务" + id + "结束,其他任务继续");
41+
cyc.await(); // 注意跟CountDownLatch不同,这里在子线程await
42+
} catch (Exception e) {
43+
e.printStackTrace();
44+
}
45+
}
46+
}
47+
}
48+
}
Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
package java0.conc0303.tool;
2+
3+
import java.util.concurrent.BrokenBarrierException;
4+
import java.util.concurrent.CyclicBarrier;
5+
6+
public class CyclicBarrierDemo2 {
7+
public static void main(String[] args) {
8+
int N = 4;
9+
CyclicBarrier barrier = new CyclicBarrier(N);
10+
11+
for(int i=0;i<N;i++) {
12+
new Writer(barrier).start();
13+
}
14+
15+
try {
16+
Thread.sleep(10000);
17+
} catch (InterruptedException e) {
18+
e.printStackTrace();
19+
}
20+
21+
System.out.println("CyclicBarrier重用");
22+
23+
for(int i=0;i<N;i++) {
24+
new Writer(barrier).start();
25+
}
26+
}
27+
static class Writer extends Thread{
28+
private CyclicBarrier cyclicBarrier;
29+
public Writer(CyclicBarrier cyclicBarrier) {
30+
this.cyclicBarrier = cyclicBarrier;
31+
}
32+
33+
@Override
34+
public void run() {
35+
System.out.println("线程"+Thread.currentThread().getName()+"正在写入数据...");
36+
try {
37+
Thread.sleep(3000); //以睡眠来模拟写入数据操作
38+
System.out.println("线程"+Thread.currentThread().getName()+"写入数据完毕,等待其他线程写入完毕");
39+
40+
cyclicBarrier.await();
41+
} catch (InterruptedException e) {
42+
e.printStackTrace();
43+
}catch(BrokenBarrierException e){
44+
e.printStackTrace();
45+
}
46+
System.out.println(Thread.currentThread().getName()+"所有线程写入完毕,继续处理其他任务...");
47+
}
48+
}
49+
}
Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
package java0.conc0303.tool;
2+
3+
import java.util.concurrent.Semaphore;
4+
5+
public class SemaphoreDemo {
6+
7+
public static void main(String[] args) {
8+
int N = 8; //工人数
9+
Semaphore semaphore = new Semaphore(5); //机器数目
10+
for (int i = 0; i < N; i++)
11+
new Worker(i, semaphore).start();
12+
}
13+
14+
static class Worker extends Thread {
15+
private int num;
16+
private Semaphore semaphore;
17+
18+
public Worker(int num, Semaphore semaphore) {
19+
this.num = num;
20+
this.semaphore = semaphore;
21+
}
22+
23+
@Override
24+
public void run() {
25+
try {
26+
semaphore.acquire(); // 在子线程里控制资源占用
27+
System.out.println("工人" + this.num + "占用一个机器在生产...");
28+
Thread.sleep(2000);
29+
System.out.println("工人" + this.num + "释放出机器");
30+
semaphore.release(); // 在子线程里控制释放资源占用
31+
} catch (InterruptedException e) {
32+
e.printStackTrace();
33+
}
34+
}
35+
}
36+
}

0 commit comments

Comments
 (0)