Executorの使用例

2589 ワード

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();

     }
 }