線程池newFixedThreadPool的使用

字號:

Examda提示: 新的線程加入后,如果正在運(yùn)行的線程達(dá)到了上限,則會阻塞,直到有了空閑的線程來運(yùn)行。
    import java.util.Random;
    import java.util.concurrent.ExecutorService;
    import java.util.concurrent.Executors;
    import java.util.concurrent.TimeUnit;
    /**
    * 線程池newFixedThreadPool的使用。
    *
    *
    *
    */
    public class ExecutorTest {
    public static void main(String args[]) {
    Random random = new Random();
    // 建立一個(gè)容量為3的固定尺寸的線程池
    ExecutorService executor = Executors.newFixedThreadPool(3);
    // 判斷可是線程池可以結(jié)束
    int waitTime = 500;
    for (int i = 0; i < 10; i++) {
    String name = "線程 " + i;
    int time = random.nextInt(1000);
    waitTime += time;
    Runnable runner = new ExecutorThread(name, time);
    System.out.println("增加: " + name + " / " + time);
    executor.execute(runner);
    }
    try {
    Thread.sleep(waitTime);
    executor.shutdown();
    executor.awaitTermination(waitTime, TimeUnit.MILLISECONDS);
    } catch (InterruptedException ignored) {
    }
    }
    }
    class ExecutorThread implements Runnable {
    private final String name;
    private final int delay;
    public ExecutorThread(String name, int delay) {
    this.name = name;
    this.delay = delay;
    }
    public void run() {
    System.out.println("啟動: " + name);
    try {
    Thread.sleep(delay);
    } catch (InterruptedException ignored) {
    }
    System.out.println("完成: " + name);
    }
    }