如何使用ExecuterService

时间:2015-06-25 08:47:05

标签: java multithreading executorservice

我正在尝试执行两个方法,其中两个方法将在一段时间后逐个执行,并且我正在使用ExecuterService。我已经实现了部分代码但是到目前为止我无法实现的全部功能,这里我发布了我的代码

public class ExampleExecuterService {

private static final int MYTHREADS = 3000;
public static void main(String[] args) throws Exception {

    ExecutorService executor = Executors.newFixedThreadPool(MYTHREADS);

    Object methodList[]={

            aMethod(),bMethod()
    };


    for(int i=0;i<methodList.length;i++){
        Object myList = methodList[i];
        Runnable worker = new MyRunnable(myList);
        executor.execute(worker);
    }
    executor.shutdown();
    // Wait until all threads are finish
            while (!executor.isTerminated()) {

            }
  System.out.println("\nFinished all threads");

}

public static class MyRunnable implements Runnable {

    private Object myList=null;

    MyRunnable(Object myList) {
        this.myList = myList;
    }
    @Override
    public void run() {


        try{

            myList.wait(2000);
        }catch(Exception e){
            e.printStackTrace();
        }
    }


}

private static Object bMethod() {
    System.out.println("This is inside method a ");
    return null;
}
private static Object aMethod() {

    System.out.println("This is inside method b ");
    return null;
}

}

我希望aMethod()bMethod()在20秒后运行,最后executer将停止。如何用我的代码做到这一点。有人请帮助我。

2 个答案:

答案 0 :(得分:5)

Object methodList[]={
   aMethod(),bMethod()
};

这不是您的方法列表。这是您的方法返回的列表(= null)。

在Java中,方法是不是对象。如果要将方法存储在列表或数组中,则必须将它们包装在对象中。通常的方法是使用Runnable接口或类似的东西。

在您的情况下,它可能如下所示:

Runnable[] methods = new Runnable[]{
   new Runnable(){  // Object wrapper for method a
       @Override
       public void run(){  // method a
          System.out.println("This is inside method a");
       }
   },
   new Runnable(){  // Object wrapper for waiting
       @Override
       public void run(){   // method to wait for 20s
          try{ Thread.sleep(20000); }catch(Exception e){}
       }
   },
   new Runnable(){  // Object wrapper for method b
       @Override
       public void run(){  // method b
          System.out.println("This is inside method b");
       }
   }
};

之后,您可以将这些“方法”数组提交给执行者服务:

ExecutorService service = Executors.newSingleThreadExecutor();
for(Runnable r : methods)
   service.submit(r);
service.shutdown();

但是,请记住ExecutorService主要是为了同时执行任务(=并行执行),而您希望按顺序执行它们。

如果你知道你总是需要一个顺序的单线程行为,你应该放弃ExecutorService而只是简单地说:

for(Runnable r : methods) 
   r.run();

编辑:完整的主要方法

public static void main(String[] args) throws Exception {

    Runnable[] methods = new Runnable[]{
       new Runnable(){  // Object wrapper for method a
           @Override
           public void run(){  // method a
              System.out.println("This is inside method a");
           }
       },
       new Runnable(){  // Object wrapper for waiting
           @Override
           public void run(){   // method to wait for 20s
              try{ Thread.sleep(20000); }catch(Exception e){}
           }
       },
       new Runnable(){  // Object wrapper for method b
           @Override
           public void run(){  // method b
              System.out.println("This is inside method b");
           }
       }
    };

    ExecutorService service = Executors.newSingleThreadExecutor();
    for(Runnable r : methods)
       service.submit(r);
    service.shutdown();

    // Wait until all threads are finish
    while (!service.isTerminated()) {}
    System.out.println("\nFinished all threads");
}

答案 1 :(得分:1)

我没有找到更好的解决方案,等待20秒,但是这个怎么样:

    ExecutorService service = Executors.newSingleThreadExecutor();
    service.submit(task1);
    service.submit(() -> {
        Thread.sleep(20000);
        return null;
    });
    service.submit(task2);