我想每 5 秒写一些 JSON。我正在使用 Jackson 编写 JSON,但它似乎阻止了我的 TimerTask。如果我不编写 JSON,则 TimerTask 每 5 秒运行一次,但是当我尝试编写 JSON 时,它会被阻止并且只运行一次。我怎样才能解决这个问题?
public class MyTimerTask extends TimerTask {
public static void main(String[] args) {
Timer timer = new Timer();
// execute MyTimerTask every 5th second
timer.scheduleAtFixedRate(new MyTimerTask(), 1000L, 5 * 1000L);
}
@Override
public void run() {
System.out.println("timertask");
// Write JSON to System.out
ObjectMapper mapper = new ObjectMapper();
try {
mapper.writeValue(System.out, "Hello");
} catch (Exception e1) {
e1.printStackTrace();
}
}
}
这是我的 Timer 线程的堆栈转储:
"Timer-0" prio=6 tid=0x02488000 nid=0x10ec in Object.wait() [0x04a6f000]
java.lang.Thread.State: TIMED_WAITING (on object monitor)
at java.lang.Object.wait(Native Method)
- waiting on <0x24577fa8> (a java.util.TaskQueue)
at java.util.TimerThread.mainLoop(Unknown Source)
- locked <0x24577fa8> (a java.util.TaskQueue)
at java.util.TimerThread.run(Unknown Source)