當前位置:編程學習大全網 - 編程軟體 - java如何創建壹個定長線程池,可控制線程最大並發數,超出的線程會在隊列中等待。求代碼

java如何創建壹個定長線程池,可控制線程最大並發數,超出的線程會在隊列中等待。求代碼

package?test;?

import?java.util.concurrent.ExecutorService;?

import?java.util.concurrent.Executors;?

public?class?ThreadPoolExecutorTest?{?

public?static?void?main(String[]?args)?{?

ExecutorService?fixedThreadPool?=?Executors.newFixedThreadPool(3);?

for?(int?i?=?0;?i?<?10;?i++)?{?

final?int?index?=?i;?

fixedThreadPool.execute(new?Runnable()?{?

public?void?run()?{?

try?{?

System.out.println(index);?

Thread.sleep(2000);?

}?catch?(InterruptedException?e)?{?

e.printStackTrace();?

}?

}?

});?

}?

}?

}

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

定長線程池的大小最好根據系統資源進行設置。如Runtime.getRuntime().availableProcessors()

  • 上一篇:DELL存儲MD3000的後面板連接器
  • 下一篇:北京蘭天馬培訓機構靠譜嗎
  • copyright 2024編程學習大全網