直接上程序:
import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors;
public class Executor {
private static final ExecutorService exec = Executors.newFixedThreadPool(3); /** * @param args */ public static void main(String[] args) {
for(int i=1;i<=5;i++){ exec.execute(new myThread(i)); } }
}
class myThread extends Thread{ int count = 0; myThread(int i){ count = i; } public void run() { System.out.println("----thread " + count + " start----"); //sleep随机秒 try { Thread.sleep(1+(int)(Math.random()*5)); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("----thread " + count + " end----"); } }
执行结果: ----thread 1 start---- ----thread 3 start---- ----thread 2 start---- ----thread 3 end---- ----thread 4 start---- ----thread 2 end---- ----thread 5 start---- ----thread 5 end---- ----thread 1 end---- ----thread 4 end----
说明: Executors.newFixedThreadPool(3),是创建固定大小是3的线程池, 最多同时处理3个任务,更多的任务需要等待,直到有线程可用~~ 线程池固定大小,不会变大,不会变小~~
(2) 如果换成Executors.newCachedThreadPool(),则创建动态大小的线程池, 任务多时,自动创建新线程,任务完毕,线程就呗咔嚓掉~~ 线程池的大小,无限制~~
结果是: ----thread 1 start---- ----thread 4 start---- ----thread 2 start---- ----thread 3 start---- ----thread 5 start---- ----thread 1 end---- ----thread 2 end---- ----thread 4 end---- ----thread 5 end---- ----thread 3 end---- 任务同时开始了~~
(3) 如果换成Executors.newSingleThreadExecutor(),即单线程的执行器~~ 结果是 ----thread 1 start---- ----thread 1 end---- ----thread 2 start---- ----thread 2 end---- ----thread 3 start---- ----thread 3 end---- ----thread 4 start---- ----thread 4 end---- ----thread 5 start---- ----thread 5 end---- 即任务依次执行。
|