JDK5中的線程池
JDK5中的一個亮點就是將Doug Lea的並發庫引入到Java標準庫中。Doug Lea確實是一個牛人,能教書,能出書,能編碼,不過這在國外還是比較普遍的,而國內的教授們就相差太遠了。
一般的服務器都需要線程池,比如Web、FTP等服務器,不過它們一般都自己實現了線程池,比如以前介紹過的Tomcat、Resin和Jetty等,現在有了JDK5,我們就沒有必要重複造車輪了,直接使用就可以,何況使用也很方便,性能也非常高。
package concurrent; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; public class TestThreadPool { public static void main(String args[]) throws InterruptedException { // only two threads ExecutorService exec = Executors.newFixedThreadPool(2); for(int index = 0; index < 100; index++) { Runnable run = new Runnable() { public void run() { long time = (long) (Math.random() * 1000); System.out.println("Sleeping " + time + "ms"); try { Thread.sleep(time); } catch (InterruptedException e) { } } }; exec.execute(run); } // must shutdown exec.shutdown(); } }
更多請看下麵的鏈接:
https://blog.sina.com.cn/s/blog_51a7b40e0100s5w9.html
最後更新:2017-04-02 06:52:12