ExecutorService_NewSingleThreadE

2017-01-03  本文已影响0人  perfect_jimmy
public class SingleThreadPool_Demo {
    public static void main(String[] agrs){
        ExecutorService threadPool = Executors.newSingleThreadExecutor();
        for(int i=1;i<5;i++){
            final int taskId = i;
            System.out.println(i);
            threadPool.execute(new Runnable(){
                
                @Override
                public void run() {
                    for(int j=1;j<5;j++){
                         try {  
                                Thread.sleep(1000*2);// 为了测试出效果,让每次任务执行都需要一定时间  
                            } catch (InterruptedException e) {  
                                e.printStackTrace();  
                            }  
                         System.out.println("第" + taskId + "次任务的第" + j + "次执行"+"-"+Thread.currentThread().getName());
                    }
                }
            });
        }
        threadPool.shutdown();// 任务执行完毕,关闭线程池  
    }
}

任务是顺序执行的,SingleThreadExecutor得到的是一个单个的线程,这个线程会保证你的任务执行完成,如果当前线程意外终止,会创建一个新线程继续执行任务,这和我们直接创建线程不同,也和newFixedThreadPool(1)不同。

1
2
3
4
第1次任务的第1次执行-pool-1-thread-1
第1次任务的第2次执行-pool-1-thread-1
第1次任务的第3次执行-pool-1-thread-1
第1次任务的第4次执行-pool-1-thread-1
第2次任务的第1次执行-pool-1-thread-1
第2次任务的第2次执行-pool-1-thread-1
第2次任务的第3次执行-pool-1-thread-1
第2次任务的第4次执行-pool-1-thread-1
第3次任务的第1次执行-pool-1-thread-1
第3次任务的第2次执行-pool-1-thread-1
第3次任务的第3次执行-pool-1-thread-1
第3次任务的第4次执行-pool-1-thread-1
第4次任务的第1次执行-pool-1-thread-1
第4次任务的第2次执行-pool-1-thread-1
第4次任务的第3次执行-pool-1-thread-1
第4次任务的第4次执行-pool-1-thread-1
上一篇 下一篇

猜你喜欢

热点阅读