`
shuaigg.babysky
  • 浏览: 552595 次
  • 性别: Icon_minigender_1
  • 来自: 济南
社区版块
存档分类
最新评论

ScheduledThreadPoolExecutor

    博客分类:
  • java
 
阅读更多

ScheduledThreadPoolExecutor
    我们先来学习一下JDK1.5 API中关于这个类的详细介绍:

    "可另行安排在给定的延迟后运行命令,或者定期执行命令。需要多个辅助线程时,或者要求 ThreadPoolExecutor 具有额外的灵活性或功能时,此类要优于 Timer。
    一旦启用已延迟的任务就执行它,但是有关何时启用,启用后何时执行则没有任何实时保证。按照提交的先进先出 (FIFO) 顺序来启用那些被安排在同一执行时间的任务。

    虽然此类继承自 ThreadPoolExecutor,但是几个继承的调整方法对此类并无作用。特别是,因为它作为一个使用 corePoolSize 线程和一个无界队列的固定大小的池,所以调整 maximumPoolSize 没有什么效果。"

    在JDK1.5之前,我们关于定时/周期操作都是通过Timer来实现的。但是Timer有以下几种危险[JCIP]

a. Timer是基于绝对时间的。容易受系统时钟的影响。
b. Timer只新建了一个线程来执行所有的TimeTask。所有TimeTask可能会相关影响
c. Timer不会捕获TimerTask的异常,只是简单地停止。这样势必会影响其他TimeTask的执行。

    如果你是使用JDK1.5以上版本,建议用ScheduledThreadPoolExecutor代替Timer。它基本上解决了上述问题。它采用相对时间,用线程池来执行TimerTask,会出来TimerTask异常。

    下面通过一个简单的实例来阐述ScheduledThreadPoolExecutor的使用。
  
    我们定期让定时器抛异常
    我们定期从控制台打印系统时间


代码如下(参考了网上的一些代码,在此表示感谢)

Java代码  收藏代码
  1. import  java.util.concurrent.ScheduledThreadPoolExecutor;  
  2. import  java.util.concurrent.TimeUnit;  
  3.   
  4.   
  5. public   class  TestScheduledThreadPoolExecutor {  
  6.       
  7.     public   static   void  main(String[] args) {  
  8.         ScheduledThreadPoolExecutor exec=new  ScheduledThreadPoolExecutor( 1 );  
  9.           
  10.         exec.scheduleAtFixedRate(new  Runnable(){ //每隔一段时间就触发异常   
  11.             @Override   
  12.             public   void  run() {  
  13.                 throw   new  RuntimeException();  
  14.             }}, 1000 5000 , TimeUnit.MILLISECONDS);  
  15.           
  16.         exec.scheduleAtFixedRate(new  Runnable(){ //每隔一段时间打印系统时间,证明两者是互不影响的   
  17.             @Override   
  18.             public   void  run() {  
  19.                 System.out.println(System.nanoTime());  
  20.             }}, 1000 2000 , TimeUnit.MILLISECONDS);  
  21.     }  
  22.   
  23. }  



总结:是时候把你的定时器换成 ScheduledThreadPoolExecutor了

分享到:
评论
5 楼 mr_xiaoyu 2017-01-05  
最终会调用到ScheduledFutureTask#run()方法, 其中有一段代码是将common运行后又重新加入队列:
       public void run() {
            boolean periodic = isPeriodic();
            if (!canRunInCurrentRunState(periodic))
                cancel(false);
            else if (!periodic)
                ScheduledFutureTask.super.run();
            else if (ScheduledFutureTask.super.runAndReset()) { //这段代码会将common重新加入队列,它调用的是FutureTask#runAndReset()方法
                setNextRunTime();
                reExecutePeriodic(outerTask);
            }
        }



Future#runAndReset()方法的代码如下:
 protected boolean runAndReset() {
        if (state != NEW ||
            !UNSAFE.compareAndSwapObject(this, runnerOffset,
                                         null, Thread.currentThread()))
            return false;
        boolean ran = false;
        int s = state;
        try {
            Callable<V> c = callable;
            if (c != null && s == NEW) {
                try {
                    c.call(); // don't set result
                    ran = true;
                } catch (Throwable ex) {
                    setException(ex);
                }
            }
        } finally {
            // runner must be non-null until state is settled to
            // prevent concurrent calls to run()
            runner = null;
            // state must be re-read after nulling runner to prevent
            // leaked interrupts
            s = state;
            if (s >= INTERRUPTING)
                handlePossibleCancellationInterrupt(s);
        }
        return ran && s == NEW;
    }

看上面的代码, 逻辑是如果抛出异常,任务就不会再被加入到队列中,自然也不会再被运行到。
4 楼 qsword555 2015-07-31  
public static void main(String[] args) {
		ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);
		
		WrapExceptionRunnable runnable = new WrapExceptionRunnable(new Runnable() {
			
			@Override
			public void run() {
				System.err.println("出现异常啦!");
				throw new RuntimeException();
			}
		});
		
		executor.scheduleAtFixedRate(
				runnable,
				1000,          //1秒后开始       
				2000,          //每隔2秒打印
				TimeUnit.MILLISECONDS);   //时间单位:毫秒
	}
	
	//保证不会有Exception抛出到线程池的Runnable,防止因为异常的抛出而导致scheduled thread停止
		public static class WrapExceptionRunnable implements Runnable{
			
			private Runnable runnable;

			public WrapExceptionRunnable(Runnable runnable) {
				this.runnable = runnable;
			}

			@Override
			public void run() {
				try {
					runnable.run();
				} catch (Throwable e) {
					e.printStackTrace();
				}
			}
		}

3 楼 yun900800 2015-05-26  
我的也是就抛了一次异常
2 楼 bjfuzh 2015-05-20  
bjfuzh 写道
我自己跑了下,那个抛异常的定时器,只执行了一次,就再也没有执行了。

是什么问题啊,lz解释下噻??????
1 楼 bjfuzh 2015-05-20  
我自己跑了下,那个抛异常的定时器,只执行了一次,就再也没有执行了。

相关推荐

Global site tag (gtag.js) - Google Analytics