定时函数抛出空指针异常
Timed functions throw null pointer exception
您好,我正在创建一个 class,我可以在其中传递函数以被称为周期性或一次性。 .问题是我传递下来的函数被立即调用,之后当它们应该被调用时我得到以下错误:
java.lang.NullPointerException
at TimedFunction.run(TimedFunction.java:41)
at java.util.TimerThread.mainLoop(Unknown Source)
at java.util.TimerThread.run(Unknown Source)
基础class如下(仅相关部分):
import java.util.concurrent.Callable;
...
public TimedFunction () {}
public void addSingleEvent (Callable func, int seconds){
//Convert to seconds from miliseconds
int time = seconds * 1000;
//Create a new timer
new java.util.Timer().schedule(
new java.util.TimerTask() {
@Override
public void run() {
try {
func.call();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
},
time
);
}
然后我做了一个测试 class 看起来像这样:
public static void main(String[] args) {
// TODO Auto-generated method stub
TimedFunction tm = new TimedFunction();
tm.addSingleEvent(helloWorld(), 5);
tm.addRepeatedEvent(dataWorld(), 1);
}
private static Callable helloWorld() {
System.out.print("Hello world!");
System.out.print(" ");
return null;
}
检查您的 helloWorld
方法 - 它返回空值!
我觉得应该是这样的
private static Callable helloWorld() {
return new Callable<String>() {
return "Hello world";
}
}
如果我不得不猜测,我认为您对如何使用 lambas 感到困惑。如果是这样,你的语法是错误的,应该是这样的:
tm.addSingleEvent(() -> "hello world", 5);
tm.addRepeatedEvent(() -> "data world", 1);
您好,我正在创建一个 class,我可以在其中传递函数以被称为周期性或一次性。 .问题是我传递下来的函数被立即调用,之后当它们应该被调用时我得到以下错误:
java.lang.NullPointerException
at TimedFunction.run(TimedFunction.java:41)
at java.util.TimerThread.mainLoop(Unknown Source)
at java.util.TimerThread.run(Unknown Source)
基础class如下(仅相关部分):
import java.util.concurrent.Callable;
...
public TimedFunction () {}
public void addSingleEvent (Callable func, int seconds){
//Convert to seconds from miliseconds
int time = seconds * 1000;
//Create a new timer
new java.util.Timer().schedule(
new java.util.TimerTask() {
@Override
public void run() {
try {
func.call();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
},
time
);
}
然后我做了一个测试 class 看起来像这样:
public static void main(String[] args) {
// TODO Auto-generated method stub
TimedFunction tm = new TimedFunction();
tm.addSingleEvent(helloWorld(), 5);
tm.addRepeatedEvent(dataWorld(), 1);
}
private static Callable helloWorld() {
System.out.print("Hello world!");
System.out.print(" ");
return null;
}
检查您的 helloWorld
方法 - 它返回空值!
我觉得应该是这样的
private static Callable helloWorld() {
return new Callable<String>() {
return "Hello world";
}
}
如果我不得不猜测,我认为您对如何使用 lambas 感到困惑。如果是这样,你的语法是错误的,应该是这样的:
tm.addSingleEvent(() -> "hello world", 5);
tm.addRepeatedEvent(() -> "data world", 1);