JDK5中的线程池


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. }   

更多请看下面的链接:

  • 1
  • 2
  • 下一页

相关内容