用Executors类中创建出的newFixedThreadPool()和newCachedThreadPool()两种方法创建的线程有什么区别
newFixedThreadPool:是创建具有固定线程容量的线程池,也就是说如果newFixedThreadPool(3)那么如果创建10个线程想要放入池中那么只能接受3个进入。
newCachedThreadPool():带缓存的线程池;具有自动扩张容量的能力;
,用Executors类创建线程又与thread类创建线程有什么区别:Executors类可以说是专门用于管理线程的工具类
public class ThreadPoulTest { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub ExecutorService ThreadPoul = Executors.newFixedThreadPool(3); //ExecutorService ThreadPoul = Executors.newCachedThreadPool(); //ExecutorService ThreadPoul = Executors.newSingleThreadExecutor(); for(int i =1;i<=10;i++){ final int data =i; ThreadPoul.execute(new Runnable(){ @Override public void run() { // TODO Auto-generated method stub for(int j =1; j<=3; j++){ try { Thread.sleep(500); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println(Thread.currentThread().getName()+" is looping of: "+j+" the task of "+data); } } } ); } System.out.println("All of 10 Thread were committed!");
} |