我正在尝试用java编写一个简单的Web服务器,但一直停止它。这是一段示例代码:
public static void main(String... args) {
args = new String[]{"stop"};
Server s = Server.getServerInstance();
s.init();
if (args.length > 0) {
for (int i = 0; i < args.length; i++) {
if (args[i].equals("start")) {
System.out.println(s);
s.start();
} else if (args[i].equals("stop")) {
System.out.println(s);
s.stop();
}
}
}
}
public class Server {
private static Server serverInstance = null;
private volatile boolean running = false;
private Thread serverthread = null;
private Server() {}
public static synchronized Server getServerInstance()
{
if(serverInstance == null)
{
serverInstance = new Server();
}
return serverInstance;
}
public void init()
{
Runnable r = new ServerThread();
serverthread = new Thread(r);
}
public void start()
{
running = true;
if(serverthread!=null)
{
serverthread.start();
}
}
public void stop()
{
running = false;
if(serverthread!=null)
{
try {
serverthread.join(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
class ServerThread implements Runnable
{
@Override
public void run() {
while(running)
{
//some action here...
System.out.println("RUNNING..");
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
我将所有这些代码打包到一个jar文件中,并使用java -cp * .jar CLASS_NAME args推荐启动和停止服务器。服务器可以启动,但永远不会被传递到stop arg中。我调试了,发现运行的布尔值永远不会改变..为什么?如何以优雅的方式实现stop方法?谢谢!!!!
答案 0 :(得分:0)
根据您的代码,我会假设您尝试停止的服务器实例不是正在运行的服务器实例。
相反,试试这个。
public static void main(String... args) {
Server s = Server.getServerInstance();
s.init();
s.start();
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
s.stop();
}
这将启动您的服务器,等待5秒钟并关闭它。
如果要停止在单独进程中运行的服务器,则需要查看使用套接字等内容来启用跨进程通信。
答案 1 :(得分:0)
我建议您使用这样的脚本(当然,如果您的Java服务器在Linux上运行)
#!/bin/sh
PROGRAM_NAME=servername
PROGRAM_HOME=/usr/local/servername
PIDFILE=/var/run/$PROGRAM_NAME.pid
application_start() {
CMDLINE="/usr/lib/java/bin/java -jar $PROGRAM_NAME.jar"
echo -n "Starting $PROGRAM_NAME daemon: $CMDLINE"
cd $PROGRAM_HOME
/usr/lib/java/bin/java -classpath lib -jar $PROGRAM_NAME.jar &
ps -Ao pid,command | grep java | grep $PROGRAM_NAME.jar | awk '{print $1}' > $PIDFILE
echo
}
application_stop() {
echo -n "Stopping $PROGRAM_NAME daemon..."
if [ -r $PIDFILE ]; then
PID=`cat $PIDFILE`
if [ $PID -gt 0 ]; then
kill $PID
echo
sleep 1
fi
rm -f $PIDFILE
fi
killall $PROGRAM_NAME
}
application_restart() {
application_stop
sleep 1
application_start
}
case "$1" in
'start')
application_start
;;
'stop')
application_stop
;;
'restart')
application_restart
;;
*)
echo "usage $0 start|stop|restart"
esac