创建数量为三的线程池并打印: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最后执行;
public static void main(String[] args) { ScheduledExecutorService scheduledThreadPool = Executors.newScheduledThreadPool(5); scheduledThreadPool.schedule(new Runnable() { public void run() { System.out.println('delay 3 seconds'); } }, 3, TimeUnit.SECONDS); } 定长线程池,3秒后执行
创建线程,实现runnable接口,此方法比较常用,class只能单继承,如果继承thread就无法继承其他的类了,但可以多实现,public class Single { public static void main(String[] args){ ExecutorService ex = Executors.newSingleThreadExecutor();
for(int i=0; i<5; i++){ runnable rn = new runnable(); ex.execute(rn); } ex.shutdown(); } } class runnable implements Runnable{ public void run(){ System.out.println(Thread.currentThread().getName()); } }
一般情况下会使用Executors创建线程池,目前不推荐,线程池不允许使用Executors去创建,而是通过ThreadPoolExecutor方式,这样的处理方式可以更加明确线程池的运行规则,规避资源耗尽的风险。