java如何使用ExecuterService以线程的形式逐个运行两个方法
我试图执行两个方法,其中两个方法将在一段时间后逐个执行,我使用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
将停止。如何使用我的代码实现这一点。谁来帮帮我
共 (0) 个答案