java实现线程池的几种方法
的有关信息介绍如下:
线程池的简单使用
创建数量为三的线程池并打印:
public class Demo {
public static void main(String[] args) {
ExecutorService tPool = Executors.newFixedThreadPool(3);
for (int i = 0; i < 10; i++) {
final int index = i;
//extends Thread 实现runable接口
tPool.execute(new Runnable() {
public void run() {
try {
System.out.println(index);
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
}
}
}
已上的执行顺序,首先执行0,1,2,但是顺序是任意的,暂停2秒钟,执行3,4,5,顺序任意的,6,7,8顺序任意的,9最后执行;
publicstaticvoidmain(String[]args){
ScheduledExecutorServicescheduledThreadPool=Executors.newScheduledThreadPool(5);
scheduledThreadPool.schedule(newRunnable(){
publicvoidrun(){
System.out.println("delay3seconds");
}
},3,TimeUnit.SECONDS);
}
定长线程池,3秒后执行
创建线程,实现runnable接口,此方法比较常用,class只能单继承,如果继承thread就无法继承其他的类了,但可以多实现,
publicclassSingle{
publicstaticvoidmain(String[]args){
ExecutorServiceex=Executors.newSingleThreadExecutor();
for(inti=0;i<5;i++){
runnablern=newrunnable();
ex.execute(rn);
}
ex.shutdown();
}
}
classrunnableimplementsRunnable{
publicvoidrun(){
System.out.println(Thread.currentThread().getName());
}
}
一般情况下会使用Executors创建线程池,目前不推荐,线程池不允许使用Executors去创建,而是通过ThreadPoolExecutor方式,
这样的处理方式可以更加明确线程池的运行规则,规避资源耗尽的风险。



