java 使用執行緒池進行多執行緒程式設計
阿新 • • 發佈:2019-02-12
package com.gxk;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;
public class ExecutorTest {
private static Integer pages=1; // 網頁數
private static boolean exeFlag=true; // 執行標識
public static void main(String[] args) {
ExecutorService executorService=Executors.newFixedThreadPool(10 ); // 建立ExecutorService 連線池預設連線10個
while(exeFlag){
if(pages<=100){
executorService.execute(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
System.out.println("爬取了第" +pages+"網頁...");
pages++;
}
});
}else{
if(((ThreadPoolExecutor)executorService).getActiveCount()==0){ // 活動執行緒個數是0
executorService.shutdown(); // 結束所有執行緒
exeFlag=false;
System.out.println("爬蟲任務已經完成" );
}
}
try {
Thread.sleep(100); // 執行緒休息0.1秒
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}