java线程池

来源:互联网 发布:淘宝卖家感谢信有创意 编辑:程序博客网 时间:2024/05/25 18:12
public class ThreadPoolTest {/** * @param args */public static void main(String[] args) {//固定线程池的方式ExecutorService threadPool = Executors.newFixedThreadPool(3);//缓存线程池的方式ExecutorService threadPool = Executors.newCachedThreadPool();//单个线程池,注意,单个线程池,当它死掉后会自动重启ExecutorService threadPool = Executors.newSingleThreadExecutor();for(int i=1;i<=10;i++){final int task = i;threadPool.execute(new Runnable(){@Overridepublic void run() {for(int j=1;j<=10;j++){try {Thread.sleep(20);} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();}System.out.println(Thread.currentThread().getName() + " is looping of " + j + " for  task of " + task);}}});}System.out.println("all of 10 tasks have committed! ");threadPool.shutdownNow();// 下面这种方式是用线程池的方式来模拟定时器的效果Executors.newScheduledThreadPool(3).scheduleAtFixedRate(new Runnable(){@Overridepublic void run() {System.out.println("bombing!");}},6,2,TimeUnit.SECONDS);}}

原创粉丝点击