import?java.util.concurrent.ExecutorService;?
import?java.util.concurrent.Executors;?
public?class?ThreadPoolExecutorTest?{?
public?static?void?main(String[]?args)?{?
ExecutorService?fixedThreadPool?=?Executors.newFixedThreadPool(3);?
for?(int?i?=?0;?i?<?10;?i++)?{?
final?int?index?=?i;?
fixedThreadPool.execute(new?Runnable()?{?
public?void?run()?{?
try?{?
System.out.println(index);?
Thread.sleep(2000);?
}?catch?(InterruptedException?e)?{?
e.printStackTrace();?
}?
}?
});?
}?
}?
}
因為線程池大小為3,每個任務輸出index後sleep 2秒,所以每兩秒打印3個數字。
定長線程池的大小最好根據系統資源進行設置。如Runtime.getRuntime().availableProcessors()