歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> JDK5中的線程池

JDK5中的線程池

日期:2017/3/1 10:52:19   编辑:Linux編程

JDK5中的一個亮點就是將Doug Lea的並發庫引入到Java標准庫中。Doug Lea確實是一個牛人,能教書,能出書,能編碼,不過這在國外還是比較普遍的,而國內的教授們就相差太遠了。

一般的服務器都需要線程池,比如Web、FTP等服務器,不過它們一般都自己實現了線程池,比如以前介紹過的Tomcat、Resin和Jetty等,現在有了JDK5,我們就沒有必要重復造車輪了,直接使用就可以,何況使用也很方便,性能也非常高。

  1. package concurrent;
  2. import java.util.concurrent.ExecutorService;
  3. import java.util.concurrent.Executors;
  4. public class TestThreadPool {
  5. public static void main(String args[]) throws InterruptedException {
  6. // only two threads
  7. ExecutorService exec = Executors.newFixedThreadPool(2);
  8. for(int index = 0; index < 100; index++) {
  9. Runnable run = new Runnable() {
  10. public void run() {
  11. long time = (long) (Math.random() * 1000);
  12. System.out.println("Sleeping " + time + "ms");
  13. try {
  14. Thread.sleep(time);
  15. } catch (InterruptedException e) {
  16. }
  17. }
  18. };
  19. exec.execute(run);
  20. }
  21. // must shutdown
  22. exec.shutdown();
  23. }
  24. }

更多請看下面的鏈接:http://www.linuxidc.com/Linux/2011-12/48496p2.htm

Copyright © Linux教程網 All Rights Reserved