線程池之-newFixedThreadPool

newFixedThreadPool 創建一個定長線程池,可控制線程最大併發數,超出的線程會在隊列中等待。

示例如下:

package com.executor.test;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author 作者:wx
 * @createDate 創建時間:Sep 17, 2019 11:13:39 AM
 */
public class FixedThreadPoolDemo {
	public static void main(String[] args) {
		ExecutorService executorService = Executors.newFixedThreadPool(3);
		for (int i = 0; i < 10; i++) {
			int temp = i;
			executorService.execute(new Runnable() {

				@Override
				public void run() {
					try {
						Thread.sleep(2000);
						System.out.println(Thread.currentThread().getName() + "," + temp);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
			});
		}
	}

}

輸出如下:

總結:因爲線程池大小爲3,每個任務輸出index後sleep 2秒,所以每兩秒打印3個數字。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章