比如現在有10個線程,但每次只想運行3個線程,當這3個線程中的任何一個運行完后,第4個線程接着補上。這種情況可以使用線程池來解決,線程池用起來也相當的簡單,不信,你看:
package com.demo; import java.util.ArrayList; import java.util.Collection; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; public class ThreadPool { private int threadCount = 10; private int threadpoolCount = 3; public void threadPoolControl() { ThreadObject[] et = new ThreadObject[threadCount]; ExecutorService service = Executors.newFixedThreadPool(threadpoolCount); Collection<ThreadObject> c = new ArrayList<ThreadObject>(); for (int i = 0; i < threadCount; i++) { et[i] = new ThreadObject(); c.add(et[i]); } try { service.invokeAll(c); service.shutdown(); } catch (InterruptedException e) { e.printStackTrace(); } } }
再加上ThreadObject類,這個類主要是線程的具體實現方法:
package com.demo; import java.util.concurrent.Callable; public class ThreadObject implements Callable<Object>{ public Object call() throws Exception { //do something...... return null; } }