多線程之線程池Executor應用,多線程executor
JDK1.5之後,提供了內建的線程池,以便我們更好的處理線程並發問題。
Executor類給我提供了多個線程池建立的方式:
建立固定的線程池 Executors.newFixedThreadPool(2)
建立可變的緩衝線程池 Executors.newCachedThreadPool()
建立單一的線程池 Executors.newSingleThreadExecutor()
先面試線程池的基本操作:
package andy.thread.test;import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;import java.util.concurrent.TimeUnit;/** * @author Zhang,Tianyou * @version 2014年11月8日 下午6:10:42 */public class ThreadPoolTest {public static void main(String[] args) {// 建立一個固定線程數的線程池ExecutorService threadPool = Executors.newFixedThreadPool(3);// 建立一個可根據需要建立新線程的緩衝線程池// ExecutorService threadPool = Executors.newCachedThreadPool();// 建立一個單一的線程池 線程死掉後將重新啟動// ExecutorService threadPool = Executors.newSingleThreadExecutor();for (int i = 0; i < 10; i++) {final int task = i;threadPool.execute(new Runnable() {@Overridepublic void run() {// TODO Auto-generated method stubfor (int j = 0; j <= 5; j++) {try {TimeUnit.SECONDS.sleep(1);} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();}System.out.println(Thread.currentThread().getName()+ " is looping of " + j + " from task " + task);}}});}// 啟動一次順序關閉,執行以前提交的任務,但不接受新任務。threadPool.shutdown();// 試圖停止所有正在執行的活動任務,暫停處理正在等待的任務,並返回等待執行的工作清單。// threadPool.shutdownNow();//執行線程的調度 6秒後執行 以後每2秒執行一次Executors.newScheduledThreadPool(3).scheduleAtFixedRate(new Runnable() {@Overridepublic void run() {System.out.println("調度了。。");}}, 6, 2, TimeUnit.SECONDS);}}
詳細可看jdk相關解釋。