Java异步任务案例

使用 CompletableFuture.allOf() 等待所有任务完成

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
package cn.idea360.assistant.dev.sync;

import java.util.concurrent.CompletableFuture;

/**
* @author cuishiying
* @date 2024-11-06
*/
public class AsyncTest1 {

/**
* 输出
* Task 1 finished
* Task 3 finished
* Task 2 finished
* All tasks completed, running next task...
*/
public static void main(String[] args) throws Exception {
// 创建多个异步任务
CompletableFuture<Void> task1 = CompletableFuture.runAsync(() -> {
try {
Thread.sleep(1000);
System.out.println("Task 1 finished");
} catch (InterruptedException e) {
e.printStackTrace();
}
});

CompletableFuture<Void> task2 = CompletableFuture.runAsync(() -> {
try {
Thread.sleep(2000);
System.out.println("Task 2 finished");
} catch (InterruptedException e) {
e.printStackTrace();
}
});

CompletableFuture<Void> task3 = CompletableFuture.runAsync(() -> {
try {
Thread.sleep(1500);
System.out.println("Task 3 finished");
} catch (InterruptedException e) {
e.printStackTrace();
}
});

// 使用 allOf 等待所有任务完成
CompletableFuture<Void> allOf = CompletableFuture.allOf(task1, task2, task3);

// 等待所有任务完成后执行后续任务
allOf.thenRun(() -> {
System.out.println("All tasks completed, running next task...");
});

// 阻塞主线程直到所有任务完成
allOf.get();
}
}

使用 CompletableFuture.anyOf() 等待任意一个任务完成

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
package cn.idea360.assistant.dev.sync;

import java.util.concurrent.CompletableFuture;

/**
* @author cuishiying
* @date 2024-11-06
*/
public class AsyncTest2 {

/**
* 输出
* Task 1 finished
* At least one task finished, running next task...
*/
public static void main(String[] args) throws Exception {
CompletableFuture<Void> task1 = CompletableFuture.runAsync(() -> {
try {
Thread.sleep(1000);
System.out.println("Task 1 finished");
} catch (InterruptedException e) {
e.printStackTrace();
}
});

CompletableFuture<Void> task2 = CompletableFuture.runAsync(() -> {
try {
Thread.sleep(2000);
System.out.println("Task 2 finished");
} catch (InterruptedException e) {
e.printStackTrace();
}
});

CompletableFuture<Void> task3 = CompletableFuture.runAsync(() -> {
try {
Thread.sleep(1500);
System.out.println("Task 3 finished");
} catch (InterruptedException e) {
e.printStackTrace();
}
});

// 使用 anyOf 等待任意一个任务完成
CompletableFuture<Void> anyOf = CompletableFuture.anyOf(task1, task2, task3).thenRun(() -> {
System.out.println("At least one task finished, running next task...");
});

anyOf.get();
}
}

使用 CompletableFuture.whenComplete() 捕获任务的完成状态

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
package cn.idea360.assistant.dev.sync;

import java.util.concurrent.CompletableFuture;

/**
* @author cuishiying
* @date 2024-11-06
*/
public class AsyncTest3 {

/**
* 输出
* Task 1 finished
* Task 3 finished
* Task 2 finished
* All tasks completed successfully!
*/
public static void main(String[] args) throws Exception {
CompletableFuture<Void> task1 = CompletableFuture.runAsync(() -> {
try {
Thread.sleep(1000);
System.out.println("Task 1 finished");
} catch (InterruptedException e) {
e.printStackTrace();
}
});

CompletableFuture<Void> task2 = CompletableFuture.runAsync(() -> {
try {
Thread.sleep(2000);
System.out.println("Task 2 finished");
} catch (InterruptedException e) {
e.printStackTrace();
}
});

CompletableFuture<Void> task3 = CompletableFuture.runAsync(() -> {
try {
Thread.sleep(1500);
System.out.println("Task 3 finished");
} catch (InterruptedException e) {
e.printStackTrace();
}
});

// 使用 whenComplete 捕获任务完成时的状态
CompletableFuture<Void> allOf = CompletableFuture.allOf(task1, task2, task3);
allOf.whenComplete((result, exception) -> {
if (exception == null) {
System.out.println("All tasks completed successfully!");
} else {
System.out.println("An error occurred: " + exception.getMessage());
}
});

allOf.get();
}
}

使用 CompletableFuture.allOf()join() 实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
package cn.idea360.assistant.dev.sync;

import java.util.concurrent.CompletableFuture;

/**
* @author cuishiying
* @date 2024-11-06
*/
public class AsyncTest4 {

/**
* 输出
* Task 1 finished
* Task 3 finished
* Task 2 finished
* All tasks completed, running next task...
* All tasks completed successfully!
*/
public static void main(String[] args) throws Exception {
// 创建多个异步任务
CompletableFuture<Void> task1 = CompletableFuture.runAsync(() -> {
try {
Thread.sleep(1000);
System.out.println("Task 1 finished");
} catch (InterruptedException e) {
e.printStackTrace();
}
});

CompletableFuture<Void> task2 = CompletableFuture.runAsync(() -> {
try {
Thread.sleep(2000);
System.out.println("Task 2 finished");
} catch (InterruptedException e) {
e.printStackTrace();
}
});

CompletableFuture<Void> task3 = CompletableFuture.runAsync(() -> {
try {
Thread.sleep(1500);
System.out.println("Task 3 finished");
} catch (InterruptedException e) {
e.printStackTrace();
}
});

// 使用 allOf 等待所有任务完成
CompletableFuture<Void> allOf = CompletableFuture.allOf(task1, task2, task3);

// 等待所有任务完成后执行后续任务
allOf.thenRun(() -> {
System.out.println("All tasks completed, running next task...");
});

// 使用 join() 等待所有任务完成
allOf.join(); // 会阻塞直到所有任务完成

// 所有任务完成
System.out.println("All tasks completed successfully!");
}
}

使用 ExecutorServiceFuture 实现自定义的任务同步

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
package cn.idea360.assistant.dev.sync;

import com.google.common.util.concurrent.ThreadFactoryBuilder;

import java.util.concurrent.*;

/**
* @author cuishiying
* @date 2024-11-06
*/
public class AsyncTest5 {

/**
* 输出
* Task 1 finished
* Task 3 finished
* Task 2 finished
* All tasks completed, running next task...
*/
public static void main(String[] args) throws Exception {
ThreadFactory threadFactory = new ThreadFactoryBuilder().setNameFormat("task-%s").build();
ExecutorService executorService = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors() * 2, threadFactory);

Future<?> task1 = executorService.submit(() -> {
try {
Thread.sleep(1000);
System.out.println("Task 1 finished");
} catch (InterruptedException e) {
e.printStackTrace();
}
});

Future<?> task2 = executorService.submit(() -> {
try {
Thread.sleep(2000);
System.out.println("Task 2 finished");
} catch (InterruptedException e) {
e.printStackTrace();
}
});

Future<?> task3 = executorService.submit(() -> {
try {
Thread.sleep(1500);
System.out.println("Task 3 finished");
} catch (InterruptedException e) {
e.printStackTrace();
}
});

// 阻塞直到所有任务完成
task1.get();
task2.get();
task3.get();

// 所有任务完成后执行后续操作
System.out.println("All tasks completed, running next task...");
executorService.shutdown();
}
}

使用 ForkJoinPool 实现并行任务

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
package cn.idea360.assistant.dev.sync;

import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.ForkJoinTask;

/**
* @author cuishiying
* @date 2024-11-06
*/
public class AsyncTest6 {

/**
* 输出
* Task 1 finished
* Task 3 finished
* Task 2 finished
* All tasks completed, running next task...
*/
public static void main(String[] args) throws Exception {
ForkJoinPool forkJoinPool = new ForkJoinPool();

// 提交任务
ForkJoinTask<?> task1 = forkJoinPool.submit(() -> {
try {
Thread.sleep(1000);
System.out.println("Task 1 finished");
} catch (InterruptedException e) {
e.printStackTrace();
}
});

ForkJoinTask<?> task2 = forkJoinPool.submit(() -> {
try {
Thread.sleep(2000);
System.out.println("Task 2 finished");
} catch (InterruptedException e) {
e.printStackTrace();
}
});

ForkJoinTask<?> task3 = forkJoinPool.submit(() -> {
try {
Thread.sleep(1500);
System.out.println("Task 3 finished");
} catch (InterruptedException e) {
e.printStackTrace();
}
});

// 等待所有任务完成
task1.join();
task2.join();
task3.join();

// 所有任务完成后执行后续操作
System.out.println("All tasks completed, running next task...");

forkJoinPool.shutdown();
}
}