Executor多執行緒框架
阿新 • • 發佈:2019-02-02
啥都別說了,上程式碼:
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);//建立ExxcutorService執行緒池 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){ //活動執行緒個數為o executorService.shutdown(); exeFlag=false; System.out.println("爬蟲任務已經完成"); } } try { Thread.sleep(100); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } }