标签:初始 exe run 工厂 code fixed .exe style override
java线程池通过Executors工厂类初始化线程池
1. 创建大小不固定的线程池
使用ExecutorService es = Executors.newCachedThreadPool();
生成大小不固定的线程池,
es.excute(任务)
public class ThreadPoolTest { public static class Taskdemo implements Runnable{ @Override public void run() { for(int i = 0;i < 10;i++){ System.out.println(Thread.currentThread().getName()+":"+i); } } } public static void main(String[] args){ ExecutorService es = Executors.newCachedThreadPool(); for(int i = 0;i< 11 ;i++){ Taskdemo tc = new Taskdemo(); es.execute(tc); } } }
2. 生成线程大小固定的线程池
ExcutorService es= Excutors.newFixedThreadPool(2);
public static void main(String[] args) { ExecutorService es=Executors.newFixedThreadPool(2); for(int i=0;i<10;i++){ Taskdemo tc=new Taskdemo(); es.execute(tc); } es.shutdown(); }
3. 生成单个线程的线程池
public static void main(String[] args){ ExecutorService es = Executors.newSingleThreadExecutor(); for(int i = 0;i< 11 ;i++){ Taskdemo tc = new Taskdemo(); es.execute(tc); } }
4. 生成一个定时的线程池
public static void main(String[] args){ ScheduledExecutorService es = Executors.newScheduledThreadPool(2); for(int i = 0;i< 11 ;i++){ Taskdemo tc = new Taskdemo(); es.scheduleAtFixedRate(tc,30,10, TimeUnit.SECONDS); } }
含义是:程序运行开始,30s开始执行,每个十秒重新执行一次。
标签:初始 exe run 工厂 code fixed .exe style override
原文地址:https://www.cnblogs.com/zhangchiblog/p/8964973.html