Skip to content

Commit 85af47c

Browse files
Future
1 parent d3da48f commit 85af47c

File tree

9 files changed

+301
-2
lines changed

9 files changed

+301
-2
lines changed

Future/Future.iml

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
<?xml version="1.0" encoding="UTF-8"?>
2+
<module type="JAVA_MODULE" version="4">
3+
<component name="NewModuleRootManager" inherit-compiler-output="true">
4+
<exclude-output />
5+
<content url="file://$MODULE_DIR$">
6+
<sourceFolder url="file://$MODULE_DIR$/src" isTestSource="false" />
7+
</content>
8+
<orderEntry type="inheritedJdk" />
9+
<orderEntry type="sourceFolder" forTests="false" />
10+
</component>
11+
</module>

Future/src/FutureAnalysis.java

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
/**
2+
* @Author: zzStar
3+
* @Date: 10-13-2020 09:34
4+
*/
5+
public class FutureAnalysis {
6+
/**
7+
* Callable & Future 的关系
8+
* Future是一个存储器,它存储了call()这个任务的结果,
9+
* 而这个任务的执行时间是无法提前确定的,因为这完全取决于call()方法执行的情况
10+
* 相互配合的关系 (运动员和终点线的裁判的关系)
11+
*/
12+
13+
/**
14+
* 注意点 ->
15+
* 当for循环批量获取future的结果时,容易发生一部分线程很慢的情况,get方法调用时应使用timeout加以限制
16+
* future的生命周期不能后退,和线程池的生命周期一样,一旦完全完成了任务,就永远停在了已完成的状态
17+
*/
18+
}

Future/src/FutureTaskUsage.java

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
import java.util.concurrent.*;
2+
3+
/**
4+
* FutureTask用法
5+
*
6+
* @Author: zzStar
7+
* @Date: 10-13-2020 10:58
8+
*/
9+
public class FutureTaskUsage {
10+
public static void main(String[] args) {
11+
Task task = new Task();
12+
FutureTask<Integer> futureTask = new FutureTask<>(task);
13+
// Thread thread = new Thread(futureTask);
14+
// thread.start();
15+
16+
ExecutorService service = Executors.newCachedThreadPool();
17+
service.submit(futureTask);
18+
service.shutdown();
19+
20+
//拿出结果
21+
try {
22+
System.out.println(futureTask.get());
23+
} catch (InterruptedException | ExecutionException e) {
24+
e.printStackTrace();
25+
}
26+
}
27+
28+
private static class Task implements Callable<Integer> {
29+
@Override
30+
public Integer call() throws Exception {
31+
System.out.println("========");
32+
Thread.sleep(3000);
33+
int sum = 0;
34+
for (int i = 0; i < 10; i++) {
35+
sum += i;
36+
}
37+
return sum;
38+
}
39+
}
40+
}

Future/src/GetException.java

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
import java.util.concurrent.*;
2+
3+
/**
4+
* 抛出异常的时机
5+
* <p>
6+
* 注意,无论自定义什么异常,get抛出的都是ExecutionException异常
7+
* 且只有执行到get方法是,才会抛出异常
8+
*
9+
* @Author: zzStar
10+
* @Date: 10-13-2020 10:12
11+
*/
12+
public class GetException {
13+
14+
public static void main(String[] args) {
15+
ExecutorService service = Executors.newCachedThreadPool();
16+
Future<Integer> future = service.submit(new CallableTask());
17+
try {
18+
System.out.println(future.isDone());
19+
System.out.println(future.get());
20+
} catch (InterruptedException e) {
21+
e.printStackTrace();
22+
System.out.println("InterruptedException");
23+
} catch (ExecutionException e) {
24+
e.printStackTrace();
25+
System.out.println("ExecutionException");
26+
}
27+
service.shutdown();
28+
}
29+
30+
private static class CallableTask implements Callable<Integer> {
31+
@Override
32+
public Integer call() throws Exception {
33+
throw new IllegalArgumentException("callable抛出异常");
34+
}
35+
}
36+
}

Future/src/MultiFutures.java

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
import java.util.ArrayList;
2+
import java.util.Random;
3+
import java.util.concurrent.*;
4+
5+
/**
6+
* 演示批量提交任务时,用list来批量接收结果
7+
*
8+
* @Author: zzStar
9+
* @Date: 10-13-2020 09:57
10+
*/
11+
public class MultiFutures {
12+
public static void main(String[] args) {
13+
ExecutorService service = Executors.newFixedThreadPool(2);
14+
ArrayList<Future> futures = new ArrayList<>();
15+
16+
for (int i = 0; i < 20; i++) {
17+
Future<Integer> future = service.submit(new CallableTask());
18+
//添加到数组中
19+
futures.add(future);
20+
}
21+
22+
//获取结果,将会每两个打印一次
23+
for (int i = 0; i < 20; i++) {
24+
var future = futures.get(i);
25+
try {
26+
System.out.println(future.get());
27+
} catch (InterruptedException | ExecutionException e) {
28+
e.printStackTrace();
29+
}
30+
}
31+
service.shutdown();
32+
}
33+
34+
private static class CallableTask implements Callable<Integer> {
35+
@Override
36+
public Integer call() throws InterruptedException {
37+
Thread.sleep(2000);
38+
return new Random().nextInt();
39+
}
40+
}
41+
}

Future/src/OneFuture.java

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
import java.util.Random;
2+
import java.util.concurrent.*;
3+
4+
/**
5+
* 演示一个Future的使用方法,get的基本用法,lambda形式
6+
*
7+
* @Author: zzStar
8+
* @Date: 10-13-2020 09:46
9+
*/
10+
public class OneFuture {
11+
public static void main(String[] args) {
12+
ExecutorService service = Executors.newCachedThreadPool();
13+
Callable<Integer> callable = () -> {
14+
Thread.sleep(2000);
15+
return new Random().nextInt();
16+
};
17+
Future<Integer> future = service.submit(callable);
18+
try {
19+
System.out.println(future.get());
20+
} catch (InterruptedException | ExecutionException e) {
21+
e.printStackTrace();
22+
}
23+
service.shutdown();
24+
}
25+
26+
/*
27+
static class CallableTask implements Callable<Integer> {
28+
@Override
29+
public Integer call() throws Exception {
30+
Thread.sleep(3000);
31+
return new Random().nextInt();
32+
}
33+
}
34+
*/
35+
}
Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
/**
2+
* 在run方法中无法抛出checked Exception
3+
* <p>
4+
* public interface Runnable {
5+
* public abstract void run();
6+
* }
7+
* 方法里声明异常,返回void
8+
*
9+
* @Author: zzStar
10+
* @Date: 10-13-2020 09:24
11+
*/
12+
public class RunnableCantThrowsException {
13+
14+
public static void main(String[] args) {
15+
Runnable runnable = () -> {
16+
//只能try catch
17+
try {
18+
throw new Exception();
19+
} catch (Exception e) {
20+
e.printStackTrace();
21+
}
22+
};
23+
}
24+
25+
}
26+
27+
/*
28+
@FunctionalInterface
29+
public interface Callable<V> {
30+
*/
31+
/**
32+
* Computes a result, or throws an exception if unable to do so.
33+
*
34+
* @return computed result
35+
* @throws Exception if unable to compute a result
36+
*//*
37+
38+
V call() throws Exception;
39+
}
40+
*/

Future/src/Timeout.java

Lines changed: 75 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,75 @@
1+
import java.util.concurrent.*;
2+
3+
/**
4+
* 演示get的超时方法
5+
* cancel方法 —> 取消任务的执行
6+
* 如果任务已经开始执行了,那么这个取消方法不会直接取消该任务,而是根据传入的参数做判断
7+
* <p>
8+
* true -> 任务能处理interrupt
9+
* false -> 仅用于避免启动尚未启动的任务(适用于未能处理interrupt、不清楚任务是否支持取消、需要等待已经开始的任务执行完成)
10+
*
11+
* @Author: zzStar
12+
* @Date: 10-13-2020 10:21
13+
*/
14+
public class Timeout {
15+
16+
private static final ExecutorService executorService = Executors.newFixedThreadPool(10);
17+
18+
static class Ad {
19+
String name;
20+
21+
public Ad(String name) {
22+
this.name = name;
23+
}
24+
25+
@Override
26+
public String toString() {
27+
return "Ad{" +
28+
"name='" + name + '\'' +
29+
'}';
30+
}
31+
}
32+
33+
//任务 -> 3秒中的时间返回广告
34+
static class FetchTask implements Callable<Ad> {
35+
@Override
36+
public Ad call() {
37+
try {
38+
Thread.sleep(3000);
39+
} catch (InterruptedException e) {
40+
System.out.println("sleep期间被中断了");
41+
return new Ad("被中断时候的默认广告");
42+
}
43+
return new Ad("Alibaba");
44+
}
45+
}
46+
47+
public void printAd() {
48+
Future<Ad> adFuture = executorService.submit(new FetchTask());
49+
Ad ad;
50+
try {
51+
//给出4秒的超时时间
52+
ad = adFuture.get(4000, TimeUnit.MILLISECONDS);
53+
} catch (InterruptedException e) {
54+
ad = new Ad("被中断时候的默认广告");
55+
} catch (ExecutionException e) {
56+
ad = new Ad("异常时候的默认广告");
57+
} catch (TimeoutException e) {
58+
ad = new Ad("超时时候的默认广告");
59+
System.out.println("超时,未获取到广告");
60+
61+
//是否中断正在执行的任务
62+
//传入false,还未被执行的任务会被标记,任务会被正常取消,未来也不会被执行
63+
boolean cancel = adFuture.cancel(false);
64+
System.out.println("cancel = " + cancel);
65+
}
66+
executorService.shutdown();
67+
System.out.println(ad);
68+
}
69+
70+
public static void main(String[] args) {
71+
Timeout timeout = new Timeout();
72+
timeout.printAd();
73+
}
74+
75+
}

README.md

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -82,5 +82,8 @@ Java并发编程
8282
期望协作工具类去实现的获取/释放等重要方法
8383
8484
85-
86-
85+
## Future
86+
Future接口
87+
主要方法
88+
FutureTask
89+
注意点

0 commit comments

Comments
 (0)