Java5线程池潜规则研究

为了研究Java5的线程池任务的执行过程,写了小例子。
为什么要研究呢,因为Java没有告诉我们什么时候是对的,什么时候是做的,面对冷冰冰的API说明,往往会迷茫。通过实例来验证才是王道!

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

/**
* 线程池的测试
*
* @author leizhimin 2009-7-7 14:15:43
*/
public class DownTask implements Runnable {
private int x;            //线程编号

public DownTask(int x) {
this.x = x;
}

public void run() {
System.out.println(x + " thread doing something!");
try {
TimeUnit.SECONDS.sleep(5L);
System.out.println("第" + x + "个线程休息完毕");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}

class FixedThreadPool {
public static void main(String[] args) {
ExecutorService exec = Executors.newFixedThreadPool(2);
for (int i = 0; i < 50; i++) {
exec.execute(new DownTask(i));
}
}
}

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wwsdwg.html