定时函数抛出空指针异常

时间:2015-09-30 11:33:20

标签: java swing time callable

嗨我正在创建一个类,我可以在其中传递要被称为周期性或一次性关闭的函数。 。问题是我传递的函数会被立即调用,之后当它们被调用时我会得到以下错误:

java.lang.NullPointerException
at TimedFunction$2.run(TimedFunction.java:41)
at java.util.TimerThread.mainLoop(Unknown Source)
at java.util.TimerThread.run(Unknown Source)

Base类如下(只有relivant部分):

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 
                );
    }
然后我做了一个看起来像这样的测试类:

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;
}

1 个答案:

答案 0 :(得分:0)

检查您的helloWorld方法 - 它返回null!

我认为它需要像

private static Callable helloWorld() {
    return new Callable<String>() {
        return "Hello world";
    }
}

如果我不得不猜测,我认为你对如何使用lambas感到困惑。如果是这种情况,你的语法是错误的,它应该是这样的:

tm.addSingleEvent(() -> "hello world", 5);
tm.addRepeatedEvent(() -> "data world", 1);