執行緒池 JDK1.5 ExecutorService threadPool = Executors.newFixedThreadPool(3)
package cn.itcast.heima2;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
public class ThreadPoolTest {
/**
* @param args
*/
public static void main(String[] args) {
//固定的執行緒池
//可以往執行緒池放n個任務,但每次執行只執行3個任務,別的任務在排隊
//ExecutorService threadPool = Executors.newFixedThreadPool(3);
//快取的執行緒池,有幾個任務幾個執行緒,動態變化
//ExecutorService threadPool = Executors.newCachedThreadPool();
//執行緒池
//單執行緒,執行緒池只有一個執行緒
ExecutorService threadPool = Executors.newSingleThreadExecutor();
for(int i=1;i<=10;i++){
final int task = i;
threadPool.execute(new Runnable(){ //往池子裡面放任務
@Override
public void run() {
for(int j=1;j<=10;j++){
try {
Thread.sleep(20);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + " is looping of " + j + " for task of " + task);
}
}
});
}
System.out.println("all of 10 tasks have committed! ");
//threadPool.shutdown();池子中沒有任務關閉執行緒,所有任務都執行完
//threadPool.shutdownNow();還有任務沒有執行完,都關閉執行緒
//執行緒池多久之間後執行任務 (任務,時間,頻率)
Executors.newScheduledThreadPool(3).schedule(new Runnable() {
@Override
public void run() {
}
}, 10, TimeUnit.SECONDS);
//多久頻率後執行
Executors.newScheduledThreadPool(3).scheduleAtFixedRate(//固定頻率
new Runnable(){
@Override
public void run() {
System.out.println("bombing!");
}},
6,
2,//每個2秒
TimeUnit.SECONDS);
}
}