package com.pure;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;
public class TestThreadPool {
public static void main(String args[]) throws InterruptedException {
ExecutorService exec = Executors.newFixedThreadPool(10, new MyThreadFactoy());
for (int index = 0; index < 10; index++) {
Runnable run = new Runnable() {
public void run() {
long time = (long) (Math.random() * 1000);
System.out.println("Sleeping " + time + "ms" + "/" + Thread.currentThread().getName());
try {
Thread.sleep(time);
} catch (InterruptedException e) {
}
}
};
exec.execute(run);
}
// must shutdown
exec.shutdown();
}
}
class MyThreadFactoy implements ThreadFactory {
@Override
public Thread newThread(Runnable r) {
Thread t = new Thread(r);
return t;
}
}
主要就是這個類的幾個方法。
類 Executors
此類中提供的一些方法有:
1.1 public static ExecutorService newCachedThreadPool()
創建一個可根據需要創建新線程的線程池,但是在以前構造的線程可用時將重用它們。對於執行很多短期異步任務的程序而言,這些線程池通常可提高程序性能。
1.2 public static ExecutorService newFixedThreadPool(int nThreads)
創建一個可重用固定線程數的線程池,以共享的無界隊列方式來運行這些線程。
1.3 public static ExecutorService newSingleThreadExecutor()
創建一個使用單個 worker 線程的 Executor,以無界隊列方式來運行該線程。
這三個方法都可以配合接口ThreadFactory的實例一起使用。並且返回一個ExecutorService接口的實例。