java中可调用的空指针异常
我正在使用executor服务来生成多个可调用线程以进行并行执行。在实现callable的类的call方法(重写)中,我检查特定的数据。如果数据存在,我将返回数据,否则我将返回null。当我执行代码时,我得到java中可调用的空指针异常,java,executorservice,callable,Java,Executorservice,Callable,我正在使用executor服务来生成多个可调用线程以进行并行执行。在实现callable的类的call方法(重写)中,我检查特定的数据。如果数据存在,我将返回数据,否则我将返回null。当我执行代码时,我得到NullPointerException。我们可以从call方法返回null吗 基本上,这种语法: public string call () { if (data) return data; else return null; } 这类的东西。是的,您可以返回null,下面是工作正常的示
NullPointerException
。我们可以从call方法返回null吗
基本上,这种语法:
public string call ()
{
if (data)
return data;
else
return null;
}
这类的东西。是的,您可以返回null,下面是工作正常的示例代码,可能在调用方法中,您访问的是一个未创建的对象
import java.util.concurrent.Callable;
import java.util.concurrent.Executors;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Future;
public class Test {
public static void main(String[] args) throws Exception {
ExecutorService executorService1 = Executors.newFixedThreadPool(4);
Future f2 =executorService1.submit(new callable());
System.out.println("f2 " + f2.get());
executorService1.shutdown();
}
}
class callable implements Callable<String> {
public String call() {
if(1==1)
return null;
return Thread.currentThread().getName();
}
}
import java.util.concurrent.Callable;
导入java.util.concurrent.Executors;
导入java.util.concurrent.ExecutorService;
导入java.util.concurrent.Future;
公开课考试{
公共静态void main(字符串[]args)引发异常{
ExecutorService executorService1=Executors.newFixedThreadPool(4);
Future f2=executorService1.submit(new callable());
System.out.println(“f2”+f2.get());
executorService1.shutdown();
}
}
类callable实现了callable{
公共字符串调用(){
如果(1==1)
返回null;
返回Thread.currentThread().getName();
}
}
是的,您可以返回null,下面是工作正常的示例代码,可能在调用方法中,您会访问未创建的对象
import java.util.concurrent.Callable;
import java.util.concurrent.Executors;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Future;
public class Test {
public static void main(String[] args) throws Exception {
ExecutorService executorService1 = Executors.newFixedThreadPool(4);
Future f2 =executorService1.submit(new callable());
System.out.println("f2 " + f2.get());
executorService1.shutdown();
}
}
class callable implements Callable<String> {
public String call() {
if(1==1)
return null;
return Thread.currentThread().getName();
}
}
import java.util.concurrent.Callable;
导入java.util.concurrent.Executors;
导入java.util.concurrent.ExecutorService;
导入java.util.concurrent.Future;
公开课考试{
公共静态void main(字符串[]args)引发异常{
ExecutorService executorService1=Executors.newFixedThreadPool(4);
Future f2=executorService1.submit(new callable());
System.out.println(“f2”+f2.get());
executorService1.shutdown();
}
}
类callable实现了callable{
公共字符串调用(){
如果(1==1)
返回null;
返回Thread.currentThread().getName();
}
}
将可调用的提交给ExecutorService
的代码是否对返回的未来
对象执行任何操作?NullPointerException发生在哪里?将可调用的提交给ExecutorService
的代码是否对返回的Future
对象执行任何操作?NullPointerException发生在哪里?