我正在尝试用 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 方法?谢谢 !!!!