我有以下RMI服务器代码:
public class ServerProgram {
public ServerProgram() {
try {
LocateRegistry.createRegistry(1097);
Calculator c = new CalculatorImpl();
String name = "rmi://host:port/name";
Naming.rebind(name, c);
System.out.println("Service is bound......");
} catch (Exception e) {
}
}
public static void main(String[] args) {
new ServerProgram();
}
}
当上述程序运行时,它会一直运行以等待客户端请求。但我不明白的是,当程序不是像while(true){};
这样的程序,以及如何阻止它听,除了停止整个程序之外,该程序是如何继续运行的?
答案 0 :(得分:5)
它继续运行的是由RMI启动的非 -daemon监听线程。要使其退出,请使用UnicastRemoteObject.unexportObject()取消绑定名称并取消导出注册表和远程对象。
答案 1 :(得分:1)
要停止它,你应该致电
LocateRegistry.getRegistry().unbind("rmi://host:port/name");
答案 2 :(得分:-2)
但是我不明白的是,当程序不是像while(true){}时那样使程序继续运行。以及如何阻止它聆听,除了停止整个程序?
这是通过修改 非 - 修改 daemon thread
完成的。请参阅:What is Daemon thread in Java?
您可以使用以下小例子测试行为:
public class DaemonThread extends Thread
{
public void run(){
System.out.println("Entering run method");
try
{
System.out.println(Thread.currentThread());
while (true)
{
try {Thread.sleep(500);}
catch (InterruptedException x) {}
System.out.println("Woke up");
}
}
finally { System.out.println("run finished");}
}
public static void main(String[] args) throws InterruptedException{
System.out.println("Main");
DaemonThread t = new DaemonThread();
t.setDaemon(false); // Set to true for testing
t.start();
Thread.sleep(2000);
System.out.println("Finished");
}
}
该设置可防止JVM关闭。在System.out.println("Finished");
之后,您仍然会看到线程正在运行"Woke up"
日志输出。