我用boolean“ thisIsServer” true运行一次,而其他时候运行false 但是方法“ message.ChangeA();”不起作用 (行System.out.println(“ message Modify”);无效) 这是主要代码:
公共班级主要{ 静态信号量锁定=新信号量(0);
public static boolean thisIsServer = false;
public static final int port = 8888;
public static Semaphore Lock = new Semaphore(0);
public static Semaphore Lock2 = new Semaphore(0);
public static Message message;
public static String command = new String();
public static void main(String[] args) throws IOException, ClassNotFoundException, InterruptedException {
if(thisIsServer){
//This is Server
Thread server = new Server();
server.start();
while (true){
Lock.acquire();
message.changeA();
//Lock2.release();
System.out.println("message modified");
}
}else{
//This is Client
Socket socket = new Socket("localhost", port);
OutputStream outputStream = socket.getOutputStream();
InputStream inputStream = socket.getInputStream();
ObjectOutputStream os = new ObjectOutputStream(socket.getOutputStream());
ObjectInputStream is = new ObjectInputStream(socket.getInputStream());
os.writeObject(new Message(10));
while(true) {
Message returnMessage = (Message) is.readObject();
System.out.println("A is : " + returnMessage.a);
os.writeObject(returnMessage);
}
}
}
}
服务器代码:
公共类服务器扩展线程{
public static final int port = 8888;
@Override
public void run() {
//This is Server
ServerSocket serverSocket = null;
try {
serverSocket = new ServerSocket(port);
Socket socket = serverSocket.accept();
ObjectOutputStream os = new ObjectOutputStream(socket.getOutputStream());
ObjectInputStream is = new ObjectInputStream(socket.getInputStream());
while (true) {
Main.message = (Message) is.readObject();
System.out.println("message received");
Main.lock.release();
synchronized (this){
wait(1000);
}
System.out.println("message sent");
os.writeObject(Main.message);
}
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
消息代码:
公共类Message实现了Serializable {
public Message(int a){
this.a = a;
}
public int a;
public void changeA(){
a = 2*a;
}
}
答案 0 :(得分:0)
我认为这是因为您将Lock定义为“ Lock”和“ lock”两种形状。 但是您已使用Lock.acquire()等待,并已在线程中解锁时使用Main.lock.release()。