java最實用newFixedThreadPool執行緒池
阿新 • • 發佈:2019-02-19
##程式碼示例
- MyTest.java
package myUtil.myUtil; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * * 自我感覺最實用的執行緒,固定長度執行緒池總結 *以及優點 */ public class MyTest{ private static final Logger logger = LoggerFactory .getLogger(MyTest.class); public static void main(String[] argv){ //建立執行緒本地變數 ThreadLocal<String> threadLocal = new ThreadLocal<String>(); /*建立可用執行緒數量的固定執行緒池*/ ExecutorService executorService = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors()); executorService.execute(new Runnable() {//向執行緒池中新增執行緒 @Override public void run() {//一定要捕獲子執行緒異常,不然它出軌了都不知道 try { } catch (Exception e) { } } }); executorService.shutdown();//一定要呼叫這個方法,不然executorService.isTerminated()永遠不為true while(true){//等待所有任務都結束了繼續執行 try { if(executorService.isTerminated()){ System.out.println("所有的子執行緒都結束了!"); break; } Thread.sleep(1000); }catch (Exception e){ e.printStackTrace(); } } } }