最近我创建了一个包含类printName(String s)
和类Timer
的函数TimerTask
。但是,当我连续使用此函数时,它显示此错误:
a
Exception in thread "Timer-1" Exception in thread "Timer-0" java.lang.NullPointerException
a
at ProxyPattern.TimerTest$1.run(TimerTest.java:21)
a
c
at java.util.TimerThread.mainLoop(Timer.java:555)
c
c
at java.util.TimerThread.run(Timer.java:505)
c
java.lang.NullPointerException
c
at ProxyPattern.TimerTest$1.run(TimerTest.java:21)
b
at java.util.TimerThread.mainLoop(Timer.java:555)
b
b
at java.util.TimerThread.run(Timer.java:505)
b
b
a
a
这是我的代码:
public class TimerTest {
Timer timer;
TimerTask timerTask;
public void printName(String s) {
timer = new Timer();
timerTask = new TimerTask() {
@Override
public void run() {
for (int i = 0; i < 5; i++) {
System.out.println(s);
}
timerTask.cancel();
timerTask = null;
}
};
timer.schedule(timerTask, 0, 1);
}
public static void main(String[] args) {
TimerTest timerTest = new TimerTest();
timerTest.printName("a");
timerTest.printName("b");
timerTest.printName("c");
}
}
我希望它打印“ a”五次,然后打印“ b”五次,最后打印“ b”五次。就是这样:
a
a
a
a
a
a
b
b
b
b
b
c
c
c
c
c
如何解决?