我需要从方法返回两种不同类型的变量(Future,ExecutorService)。我该怎么走?这是一段代码.. 我有一个A类,我试图在' B'中调用run()方法。类。 ' startExecutorService'是启动threadExecutor和的方法 ' stopExecutorService'是停止threadExecutor的方法
public class A{
public static void main(String[] args){
A AObj= new A();
Future<?> task = null;
ExecutorService threadexec = null;
task = AObj.startExecutorService(task, threadexec);
AObj.stopExecutorService(task, threadexec);
}
public Future<?> startExecutorService(Future<?> control, ExecutorService threadExecutor){
//'noOfThreads' determines the total no of threads to be created in threadpool
int noOfThreads = 1;
// Creating an object for class 'B' which has the run() method
B ThreadTaskOne = new ExecutorServiceThreadClass();
// Calling the ExecutorService to create Threadpool with specified number of threads
threadExecutor = Executors.newFixedThreadPool(noOfThreads);
// Creating a Future object 'control' and thereby starting the thread 'ThreadTaskOne'
control = threadExecutor.submit(ThreadTaskOne);
return control;
}
public void stopExecutorService(Future<?> task, ExecutorService threadExecutor){
// Interrupting the thread created by threadExecutor
task.cancel(true);
if(task.isCancelled()){
System.out.println("Task has been cancelled !!");
}
// Closing the threadExecutor
threadExecutor.shutdownNow();
}
}
我得到了&#39; NullPointerException异常&#39; at&#39; stopExecutorService&#39; line in line&#39; threadExecutor.shutdownNow();&#39;出现此错误的原因是, threadExecutor值在main方法中没有改变。它仅在&#39; startExecutorService&#39;中发生了变化。方法。所以我想返回更改后的值 threadExecutor返回main方法,以及Future ..
请帮助我
答案 0 :(得分:2)
创建一个复合类并返回该类的对象?
class A{
}
class B{
}
class Composite{
A varA;
B varB;
public Composite(A ax, B by){ varA = ax; varB = by;}
public A returnA(){ return varA;}
public B returnB(){ return varB;}
}
class Executor{
A a;
B b;
////// code here
public Composite returnComposite{
Composite c = new Composite(a,b);
return c;
}
}