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