java程序設計線程池(newCachedThreadPool())


  創建一個無界的可緩存的線程池,若線程長時間沒用會自動銷毀,直接上代碼好了:

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class Threadd3 {

    public static void main(String[] args) {
        ExecutorService es = Executors.newCachedThreadPool();
        run r = new run();
        es.execute(r);
        es.execute(r);
        es.execute(r);
        es.execute(r);
        es.shutdown();
    }

}

class run implements Runnable {

    @Override
    public void run() {
        // TODO Auto-generated method stub
        System.out.println(Thread.currentThread().getName());
    }
    
}

  先構造一個線程池對象,實現一個Runnable接口的對象,隨后執run()方法,並不是只有一個線程執行,輸出如下:

  pool-1-thread-2
  pool-1-thread-4
  pool-1-thread-1
  pool-1-thread-3


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM