1,線程池對象
1,Executors 工廠類
-
方法 newFixedThreadPool(int num),創建固定個數線程池,num 代表線程個數
-
方法 newCachedThreadPool(),創建彈性個數的線程池,當忙碌時,會不斷創建線程,當空閑時,會回收線程
2,ExecutorService 線程池
3,線程計數器 CountDownLatch
- new CountDownLatch(10),一般實例化會傳入具體等待幾個線程
- countDownLatch.countDown(),會把傳入的值 減一,當數字是 0 的時候會繼續往下執行
- countDownLatch.await(60, TimeUnit.HOURS) ,等待countDownLatch.countDown()將傳入的值減到0,當超時的時候也會繼續往下執行
2,簡單的使用
package com.hwq.admin.back.service;
import com.hwq.common.exception.ServerException;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
@Service
public class ThreadPoolService {
private final ExecutorService executorService = Executors.newFixedThreadPool(5);
public List<String> listPoolName() {
CountDownLatch countDownLatch = new CountDownLatch(10);
List<String> list = new ArrayList<>();
List<String> synList = Collections.synchronizedList(list); // 注意線程安全
for (int i = 0; i < 10; i++) {
executorService.execute(() -> {
try {
Thread.sleep(1000);
Thread t = Thread.currentThread();
synList.add(t.getId() + " : " + t.getName());
countDownLatch.countDown(); // 通知計數器完成任務
} catch (InterruptedException e) {
e.printStackTrace();
}
});
}
try {
countDownLatch.await(60, TimeUnit.SECONDS); // 線程等待
return list;
} catch (InterruptedException ex) {
throw new ServerException(ex);
}
}
}
浙公網安備 33010602011771號