Executor 的使用实例

class SerialExecutor implements Executor {
     final Queue<Runnable> tasks = new ArrayDeque<Runnable>();
     final Executor executor;  //添加这个进来的目的就是为了执行executor中的execute()方法。
     Runnable active;

     SerialExecutor(Executor executor) {
         this.executor = executor;
     }

     public synchronized void execute(final Runnable r) {
         //这里没有run()方法哦!
         tasks.offer(new Runnable() {  //这里只是放进去,并没有执行
             public void run() {
                 try {
                     r.run();                     //3
                 } finally {
                     scheduleNext();
                 }
             }
         });

         if (active == null) {
             scheduleNext();  //放进去,又取出来了,tasks中没有了
         }
     }

     protected synchronized void scheduleNext() {
         if ((active = tasks.poll()) != null) {         //active中有run()方法。
             executor.execute(active);             //1 若把executor改成this,就不能得到数据了,
                                                   //因为它的execute()方法中没有run()方法。
         }
     }

     public void display()
     {
         if(tasks.isEmpty())
             System.out.println("this is null");
         for(Runnable r :tasks)
         {
             System.out.println(r.toString());
         }
     }

     public static void main(String[] args)
     {
         Runnable r1 = new Runnable(){
            public void run() {
                int i = 0;
                System.out.println("i = " +(++i));
            }
         };
         Runnable r2 = new Runnable(){
            public void run() {
                int a = 3;
                System.out.println("a = " +(++a));
            }
         };
         Runnable r3 = new Runnable(){
            public void run() {
                int b = 7;
                System.out.println("b = " +(++b));
            }
         };

         SerialExecutor executor = new SerialExecutor(new Executor(){
            public void execute(Runnable command) {
                command.run();             //2
            }
         });

         executor.execute(r1);
         executor.execute(r2);
         executor.execute(r3);
         executor.display();

     }
 }

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值