我想每隔5秒寫一些JSON。我使用傑克遜寫JSON,但它似乎阻止我的TimerTask。如果我不寫JSON,則TimerTask每隔5秒運行一次,但是當我嘗試寫JSON時,它被阻塞並且只運行一次。我怎樣才能解決這個問題?使用Jackson寫入JSON塊我的TimerTask
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-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)
你有解決方案嗎? – Jonas 2011-05-04 18:55:31
首先序列化爲一個字符串,然後打印出結果(可能帶有尾隨換行符) – StaxMan 2011-05-13 21:28:35