多線程之線程池Executor應用,多線程executor

來源:互聯網
上載者:User

多線程之線程池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相關解釋。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.