java并发

This commit is contained in:
罗祥 2019-11-29 17:58:46 +08:00
parent 3f371f110d
commit 538f89ebc9
14 changed files with 913 additions and 114 deletions

View File

@ -31,6 +31,7 @@ public class J5_AtomicIntegerFieldUpdater {
CountDownLatch latch = new CountDownLatch(number);
ExecutorService executorService = Executors.newFixedThreadPool(10);
Candidate candidate = new Candidate("候选人", 0);
// 使用字段更新型来保证其线程安全
AtomicIntegerFieldUpdater<Candidate> fieldUpdater = AtomicIntegerFieldUpdater.newUpdater(Candidate.class, "score");
for (int i = 0; i < number; i++) {
executorService.execute(new Task(latch, candidate, fieldUpdater));

View File

@ -0,0 +1,22 @@
package com.heibaiying.createThread;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
public class J3_Method03 {
public static void main(String[] args) throws ExecutionException, InterruptedException {
Task task = new Task();
FutureTask<Integer> futureTask = new FutureTask<>(task);
new Thread(futureTask).start();
System.out.println("获得线程返回值:" + futureTask.get());
}
}
class Task implements Callable<Integer> {
@Override
public Integer call() {
return 100;
}
}

View File

@ -0,0 +1,22 @@
package com.heibaiying.future;
import java.util.concurrent.*;
public class J0_Callable {
static class Task implements Callable<Integer> {
@Override
public Integer call() throws InterruptedException {
Thread.sleep(3000);
return 100;
}
}
public static void main(String[] args) throws ExecutionException, InterruptedException {
ExecutorService executors = Executors.newSingleThreadExecutor();
Future<Integer> future = executors.submit(new Task());
System.out.println("计算结果为:" + future.get());
executors.shutdown();
}
}

View File

@ -1,43 +0,0 @@
package com.heibaiying.future;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;
public class J1_Future {
static class Task implements Callable<Integer> {
private int operator;
Task(Integer operator) {
this.operator = operator;
}
@Override
public Integer call() throws Exception {
Thread.sleep(500);
return operator * 10;
}
}
public static void main(String[] args) {
ExecutorService executors = Executors.newFixedThreadPool(20);
List<Future<Integer>> futureList = new ArrayList<>();
for (int i = 0; i <= 100; i++) {
Future<Integer> submit = executors.submit(new Task(i));
futureList.add(submit);
}
// 获取所有线程的返回值并计算
Integer reduce = futureList.stream().map(x -> {
try {
return x.get();
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
}
return 0;
}).reduce(0, Integer::sum);
System.out.println("计算结果为:" + reduce);
executors.shutdown();
}
}

View File

@ -0,0 +1,26 @@
package com.heibaiying.future;
import java.util.concurrent.*;
public class J1_FutureTask {
static class Task implements Callable<Integer> {
@Override
public Integer call() throws InterruptedException {
Thread.sleep(3000);
return 100;
}
}
public static void main(String[] args) throws ExecutionException, InterruptedException {
FutureTask<Integer> futureTask01 = new FutureTask<>(new Task());
FutureTask<Integer> futureTask02 = new FutureTask<>(new Task());
new Thread(futureTask01).start();
ExecutorService executorService = Executors.newSingleThreadExecutor();
executorService.submit(futureTask02);
System.out.println("futureTask01 计算结果为:" + futureTask01.get());
System.out.println("futureTask02 计算结果为:" + futureTask01.get());
executorService.shutdown();
}
}

View File

@ -26,15 +26,16 @@ public class J2_CompletableFuture {
}
public static void main(String[] args) throws InterruptedException {
int intermediateResult;
CompletableFuture<Integer> future = new CompletableFuture<>();
System.out.println("主线程开始计算");
// 启动子线程
new Thread(new Compute(future)).start();
int i = 0;
for (int j = 0; j < 100; j++) {
i = i + j;
}
System.out.println("启动主线程");
Thread.sleep(2000);
System.out.println("主线程计算完成");
future.complete(i);
// 假设主线程计算结果为 100
intermediateResult = 100;
// 传递主线程的计算结果给子线程
future.complete(intermediateResult);
}
}

View File

@ -6,17 +6,13 @@ import java.util.concurrent.ExecutionException;
public class J3_SupplyAsync {
private static Integer compute() {
int i = 0;
for (int j = 0; j < 100; j++) {
i = i + j;
}
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("子线程计算完成");
return i;
return 100;
}
public static void main(String[] args) throws ExecutionException, InterruptedException {

View File

@ -38,6 +38,6 @@ public class J4_StreamingCall {
.thenApply(J4_StreamingCall::multi)
.thenAccept(J4_StreamingCall::accept) //值在这一步被消费掉了
.thenAccept(x -> System.out.println("运算结果:" + x));
future.get(); //惰性求值如果缺少这一步不会有任何输出
future.get(); //类似于流式计算的惰性求值如果缺少这一步不会有任何输出
}
}

View File

@ -0,0 +1,33 @@
package com.heibaiying.lockOptimization;
import java.util.Date;
public class Employee {
private String name;
private int age;
private Date birthday;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
}

View File

@ -0,0 +1,17 @@
package com.heibaiying.lockOptimization;
/**
* 锁消除
*/
public class LockElision {
private String toJson(Employee employee) {
StringBuffer buffer = new StringBuffer();
buffer.append("name:").append(employee.getName());
buffer.append("age:").append(employee.getAge());
buffer.append("birthday:").append(employee.getBirthday());
return buffer.toString();
}
}

View File

@ -23,9 +23,11 @@ public class J2_ThreadSafe {
@Override
public void run() {
try {
// 如果当前线程中不存在该值则创建一个
if (threadLocal.get() == null) {
threadLocal.set(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
}
// 使用线程私有的SimpleDateFormat
Date parse = threadLocal.get().parse("2018-08-08 08:08:08");
System.out.println(parse);
atomicInteger.incrementAndGet();

View File

@ -0,0 +1,23 @@
package com.heibaiying.threadPool;
import java.util.concurrent.*;
public class J5_GetThreadResult {
static class CustomThread implements Callable<String> {
@Override
public String call() throws Exception {
Thread.sleep(3000);
return "线程返回结果";
}
}
public static void main(String[] args) throws ExecutionException, InterruptedException {
ExecutorService executorService = Executors.newSingleThreadExecutor();
Future<String> submit = executorService.submit(new CustomThread());
String result = submit.get();
System.out.println(result);
executorService.shutdown();
}
}

File diff suppressed because it is too large Load Diff

View File

@ -1400,7 +1400,6 @@ public class Test {
##### 3.合理优化线程池的数量
<div align="center"> <img src="../pictures/合理线程池数量.png"/> </div></br>
#### 3.2.3 Fork/Join 框架
ForkJoin主要提供了两个主要的执行任务的接口。RecurisiveAction与RecurisiveTask
@ -1626,7 +1625,8 @@ CAS的全称是Compare And Swap 即比较交换,其算法核心思想如下
如果V值等于E值则将V的值设为N。若V值和E值不同则说明已经有其他线程做了更新则当前线程什么都不做。通俗的理解就是CAS操作需要我们提供一个期望值当期望值与当前线程的变量值相同时说明还没线程修改该值当前线程可以进行修改也就是执行CAS操作但如果期望值与当前线程不符则说明该值已被其他线程修改此时不执行更新操作但可以选择重新读取该变量再尝试再次修改该变量也可以放弃操作。
<div align="center"> <img src="https://github.com/heibaiying/LearningNotes/blob/master/pictures/原子包.png"/> </div></br>
<div align="center"> <img src="../pictures/原子包.png"/> </div></br>
```java
// 原子类
public class Test {