上篇文章講了前兩種實現方法,接下來會爲大家展現後兩種方法是如何實現的
三、實現Callable接口
-
與使用Runnable相比, Callable功能更強大些
-
實現的call()方法相比run()方法,可以返回值
-
方法可以拋出異常
-
支持泛型的返回值
-
需要藉助FutureTask類,比如獲取返回結果
class CallableTest implements Callable<Integer> {
@Override
public Integer call() throws Exception {
int sum = 0;
for (int i = 0; i < 10; i++) {
System.out.println(Thread.currentThread().getName() + ":" + i);
sum += i;
}
return sum;
}
}
public class Test {
public static void main(String[] args) {
// 實現Callable<> 有返回值
CallableTest callableTest = new CallableTest();
FutureTask<Integer> futureTask = new FutureTask<>(callableTest);
new Thread(futureTask, "方式三").start();
// 返回值
try {
Integer integer = futureTask.get();
System.out.println("返回值(sum):" + integer);
} catch (Exception e) {
e.printStackTrace();
}
}
}
四、使用線程池
說明:
-
提前創建好多個線程,放入線程池中,使用時直接獲取,使用完放回池中。可以避免頻繁創建銷燬、實現重複利用。類似生活中的公共交通工具。
好處:
-
提高響應速度(減少了創建新線程的時間)
-
降低資源消耗(重複利用線程池中線程,不需要每次都創建)
-
便於線程管理
class ThreadPool implements Runnable {
@Override
public void run() {
for (int i = 0; i < 10; i++) {
System.out.println(Thread.currentThread().getName() + ":" + i);
}
}
}
// 線程池
public class Test {
public static void main(String[] args) {
ExecutorService pool = Executors.newFixedThreadPool(10);
ThreadPoolExecutor executor = (ThreadPoolExecutor) pool;
/*
* 可以做一些操作:
* corePoolSize:核心池的大小
* maximumPoolSize:最大線程數
* keepAliveTime:線程沒任務時最多保持多長時間後會終止
*/
executor.setCorePoolSize(5);
// 開啓線程
executor.execute(new ThreadPool());
executor.execute(new ThreadPool());
executor.execute(new ThreadPool());
executor.execute(new ThreadPool());
}
}
}
注:本文爲Wayne原創,未經許可不得在任何平臺轉載。如需轉載,與作者聯繫~
關注微信公衆號:智識訓練營(微信ID:TechBootcamp),獲取更多資訊~