我想在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命令的* .jar CLASS_NAME ARGS讚揚啓動和停止服務器。服務器可以啓動,但從未停止傳遞給停止參數。我調試,發現布爾值運行永遠不會改變......爲什麼?我如何以優雅的方式實現停止方法?謝謝 !!!!
當你運行java第二次,它創建了一個全新的過程中,的。 stop()'調用沒有以任何方式連接到第一個進程啓動的s。 – Thomas 2013-04-23 02:36:44
爲什麼'tomcat'? – leonbloy 2013-04-23 02:36:52
你需要一個啓動/停止腳本 – 2013-04-23 02:37:58