gpt4 book ai didi

java - 如何在特定时间退出java程序

转载 作者:行者123 更新时间:2023-11-29 08:12:55 26 4
gpt4 key购买 nike

我有一个 JMS 监听器应用程序,QueueReceive 类实现了 MessageListener。主要功能如下:

public static void main(String[] args) throws Exception {

InitialContext ic = getInitialContext();
QueueReceive qr = new QueueReceive();
qr.init(ic, QUEUE);

System.out.println("JMS Ready To Receive Messages (
To quit, send a \"quit\" message).");
// Wait until a "quit" message has been received.

synchronized(qr) {
while (! qr.quit) {
try {
qr.wait();
} catch (InterruptedException ie) {}
}
}
qr.close();
}

有没有办法在程序中的特定时间不通过 jms 消息退出应用程序?

最佳答案

您可以使用 TimerTask [ Sample Code ] 为此目的。

示例:

import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;

public class ExitOn {
Timer timer = new Timer();
TimerTask exitApp = new TimerTask() {
@Override
public void run() {
System.exit(0);
}
};
public ExitOn() {
timer.schedule(exitApp, new Date(System.currentTimeMillis()+5*1000));//Exits after 5sec of starting the app
while(true)
System.out.println("hello");
}

public static void main(String[] args) {
new ExitOn();
}
}

关于java - 如何在特定时间退出java程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6923928/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com