import java.io.IOException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; public class Test { public static void main(String[] args) throws IOException, InterruptedException { ExecutorService service = Executors.newFixedThreadPool(2); for (int i = 0; i < 6; i++) { final int index = i; System.out.println("task: " + (i+1)); Runnable run = new Runnable() { @Override public void run() { System.out.println("thread start" + index); try { Thread.sleep(Long.MAX_VALUE); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("thread end" + index); } }; service.execute(run); } } }
輸出:task: 1
task: 2
thread start0
task: 3
task: 4
task: 5
task: 6
task: 7
thread start1
task: 8
task: 9
task: 10
task: 11
task: 12
task: 13
task: 14
task: 15
從執行個體可以看到for迴圈並沒有被固定的線程池阻塞住,也就是說所有的線程task都被提交到了ExecutorService中,查看 Executors.newFixedThreadPool()如下:
public static ExecutorService newFixedThreadPool(int nThreads) {
return new ThreadPoolExecutor(nThreads, nThreads,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>());
}
可以看到task被提交都了LinkedBlockingQueue中。這裡有個問題,如果工作清單很大,一定會把記憶體撐爆,如何解決?看下面:
import java.io.IOException; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.BlockingQueue; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; public class Test { public static void main(String[] args) throws IOException, InterruptedException { BlockingQueue<Runnable> queue = new ArrayBlockingQueue<Runnable>(3); ThreadPoolExecutor executor = new ThreadPoolExecutor(3, 3, 1, TimeUnit.HOURS, queue, new ThreadPoolExecutor.CallerRunsPolicy()); for (int i = 0; i < 10; i++) { final int index = i; System.out.println("task: " + (index+1)); Runnable run = new Runnable() { @Override public void run() { System.out.println("thread start" + (index+1)); try { Thread.sleep(Long.MAX_VALUE); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("thread end" + (index+1)); } }; executor.execute(run); } } }
輸出:task: 1
task: 2
thread start1
task: 3
task: 4
task: 5
task: 6
task: 7
thread start2
thread start7
thread start6
線程池最大值為4(??這裡我不明白為什麼是設定值+1,即3+1,而不是3),準備執行的任務隊列為3。可以看到for迴圈先處理4個task,然後把3個放到隊列。這樣就實現了自動阻塞隊列的效果。記得要使用ArrayBlockingQueue這個隊列,然後設定容量就OK了。
轉載網址: http://heipark.iteye.com/blog/1393847