使用java自帶線程池


 

java提供自帶的線程池,而不需要自己去開發一個自定義線程池了。

線程池類 ThreadPoolExecutor在包java.util.concurrent下

 
ThreadPoolExecutor threadPool= new ThreadPoolExecutor(10, 15, 60, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>());
 


第一個參數10 表示這個線程池初始化了10個線程在里面工作
第二個參數15 表示如果10個線程不夠用了,就會自動增加到最多15個線程
第三個參數60 結合第四個參數TimeUnit.SECONDS,表示經過60秒,多出來的線程還沒有接到活兒,就會回收,最后保持池子里就10個
第四個參數TimeUnit.SECONDS 如上
第五個參數 new LinkedBlockingQueue() 用來放任務的集合

execute方法用於添加新的任務
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
package  multiplethread;
   
import  java.util.concurrent.LinkedBlockingQueue;
import  java.util.concurrent.ThreadPoolExecutor;
import  java.util.concurrent.TimeUnit;
   
public  class  TestThread {
   
     public  static  void  main(String[] args)  throws  InterruptedException {
           
         ThreadPoolExecutor threadPool=  new  ThreadPoolExecutor( 10 15 60 , TimeUnit.SECONDS,  new LinkedBlockingQueue<Runnable>());
           
         threadPool.execute( new  Runnable(){
   
             @Override
             public  void  run() {
                 // TODO Auto-generated method stub
                 System.out.println( "任務1" );
             }
               
         });
   
     }
   
}


免責聲明!

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



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