forked from lihengming/java-codes
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathExecutorTest.java
More file actions
49 lines (44 loc) · 1.41 KB
/
Copy pathExecutorTest.java
File metadata and controls
49 lines (44 loc) · 1.41 KB
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
package juc;
import java.util.concurrent.*;
/**
* Created by on 2017/6/18.
*/
public class ExecutorTest {
public static void main(String[] args) {
//创建固定线程数的线程池
ExecutorService es = Executors.newFixedThreadPool(2);////
//执行传统Runnable任务
es.execute(new RunnableTask());
//执行Callable任务并获得任务结果Future
System.out.println("put time:" + System.currentTimeMillis());
Future future = es.submit(new CallableTask());
try {
System.out.println("get time:" + System.currentTimeMillis());
System.out.println("Calculate Completed Sum:" + future.get());
} catch (InterruptedException | ExecutionException e) {//
e.printStackTrace();
}
//关键线程池
es.shutdown();
/**
输出:
pool-1-thread-1 Started By Runnable
pool-1-thread-2 Started By Callable
Calculate Completed Sum:2
*/
}
}
class CallableTask implements Callable {
@Override
public Object call() throws Exception {
System.out.println(Thread.currentThread().getName() + " Started By Callable");
//求和
return 1 + 1;
}
}
class RunnableTask implements Runnable {
@Override
public void run() {
System.out.println(Thread.currentThread().getName() + " Started By Runnable");
}
}