我有一個要求如下在java中循環一定時間和一定的任務
loop(N times)
{
for(1 minute)
{
write certain values to a tree map
}
for(exactly after that above 1 min task)
{
serialize the tree map
return the tree map
create a new tree map
}
}
我如何實現這一點?
這是我迄今所做..
public class StoreMessage {
private static long start_nanotime=System.nanoTime();
private static Thread thisThread = Thread.currentThread();
private static int timeToRun = 60000; // 1 minute
private static byte[] b=null;
public static Map <Long,Message> map1=new TreeMap<Long,Message>();
public static byte[] store(Message message){
new Thread(new Runnable(){
public void run(){
try{
sleep(timeToRun);
thisThread.interrupt();
b=serializer.serialize(map1);
new TreeMap<Long,Message>();
} catch(Exception e){
e.printStackTrace();
}
}
}).start();
while (!Thread.interrupted()) {
long precise_time=TimeUnit.MILLISECONDS.toNanos(System.currentTimeMillis())+(System.nanoTime()-start_nanotime);
map1.put(precise_time, message);
}
return b;
}
}
我試圖將收到存儲在一分鐘到一棵樹地圖針對其精確的時間key.After類郵件的所有JMS對象完成一分鐘,我希望序列化該映射並將字節[]返回給另一個類。同時我創建一個新的樹形圖來存儲下一組JMS消息一分鐘 這段代碼有些不能工作。它給我錯誤java.lang.OutOfMemoryError:Java堆空間。另外我注意到它一直只寫一條消息給地圖,即如果消息是「嗨」,「對你很好的一天」 - 這是兩條jms消息; StoreMessage類一次接收一條消息......它會首先收到「hi」,一旦處理完這條消息,它就會檢索下一條消息。但是我注意到,整整一分鐘,當線程沒有中斷時,它只會將第一條消息寫入地圖並給出錯誤。我如何解決這些問題?
你到目前爲止寫了些什麼? – doNotCheckMyBlog 2012-04-03 10:04:10
通過閱讀[相應的Java教程](http://docs.oracle.com/javase/tutorial/java/nutsandbolts/for.html)[和Javadoc](http://docs.oracle.com/javase/6 /docs/api/java/lang/Object.html#wait%28long%29)先? – 2012-04-03 10:04:11
一分鐘是60秒。所以雖然時差比60秒低。做一些操作。 – 2012-04-03 10:04:48