JDK5中的线程池
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();
- }
- }
更多请看下面的链接:
|
评论暂时关闭