是否可以通过共享远程对象同步两个线程?
Is it possible to synchronize two threads over shared Remote Object?
public class RMIClient {
public static void main(String[] args) {
String serverURL = "rmi://" + args[0] + "/GameServer";
String viewURL = "rmi://" + args[0] + "/ViewServer";
try {
GameInterface gameIntf = (GameInterface)Naming.lookup(serverURL);
PlayerView view = (PlayerView)Naming.lookup(viewURL);
while(!gameIntf.getGameOver()){
synchronized(GameInterface.sharedObject){
GameInterface.sharedObject.notify();
System.out.println(view.getMessage());
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
if(br.readLine().contains("y"))
gameIntf.setNextMove(true);
GameInterface.sharedObject.wait();
}
}
} catch (MalformedURLException | RemoteException | NotBoundException e1) {
e1.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public interface GameInterface extends Remote{
public static final Object sharedObject = new Object();
public void setNextMove(boolean val) throws RemoteException;
public boolean getGameOver() throws RemoteException;
}
目前,当我启动 rmiregistry、服务器并启动两个 RMI 客户端时,两个客户端在获得第一个输入 i 后永远等待。 e.一个客户没有通知其他客户。我在同一个 JVM 上启动 RMI 客户端。
没有。客户端的存根对象与服务器主机中的远程服务器不同 Java 对象,在它上面同步或通知它不会神奇地通过网络传播到服务器或其他客户端。
link you cited 中的答案也不支持您的理论。你需要阅读@MarcH 和我的答案,忽略其他的,这些答案在各个方面都是错误的。
public class RMIClient {
public static void main(String[] args) {
String serverURL = "rmi://" + args[0] + "/GameServer";
String viewURL = "rmi://" + args[0] + "/ViewServer";
try {
GameInterface gameIntf = (GameInterface)Naming.lookup(serverURL);
PlayerView view = (PlayerView)Naming.lookup(viewURL);
while(!gameIntf.getGameOver()){
synchronized(GameInterface.sharedObject){
GameInterface.sharedObject.notify();
System.out.println(view.getMessage());
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
if(br.readLine().contains("y"))
gameIntf.setNextMove(true);
GameInterface.sharedObject.wait();
}
}
} catch (MalformedURLException | RemoteException | NotBoundException e1) {
e1.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public interface GameInterface extends Remote{
public static final Object sharedObject = new Object();
public void setNextMove(boolean val) throws RemoteException;
public boolean getGameOver() throws RemoteException;
}
目前,当我启动 rmiregistry、服务器并启动两个 RMI 客户端时,两个客户端在获得第一个输入 i 后永远等待。 e.一个客户没有通知其他客户。我在同一个 JVM 上启动 RMI 客户端。
没有。客户端的存根对象与服务器主机中的远程服务器不同 Java 对象,在它上面同步或通知它不会神奇地通过网络传播到服务器或其他客户端。
link you cited 中的答案也不支持您的理论。你需要阅读@MarcH 和我的答案,忽略其他的,这些答案在各个方面都是错误的。