Java并行执行任务

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
/**
* 并行执行任务
*/
public class TestFuture {

@Test
public void test(){

CompletableFuture<String> future1 = CompletableFuture.supplyAsync(() -> method1());
CompletableFuture<String> future2 = CompletableFuture.supplyAsync(() -> method2());

try {
System.out.println(future1.get());
System.out.println(future2.get());
}catch (Exception e){

}

}

public String method1(){
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
e.printStackTrace();
}
return "method1";
}

private String method2(){
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
e.printStackTrace();
}
return "method2";
}

}