gpt4 book ai didi

java - 我需要同步吗?

转载 作者:行者123 更新时间:2023-12-01 15:04:37 25 4
gpt4 key购买 nike

我需要添加某种同步吗?我创建了另一个线程来管理与服务器的 TCP 通信。流程是这样的:

private void sendLetterButtonActionPerformed(java.awt.event.ActionEvent evt) {                                                 
try {
// TODO add your handling code here:
session.getCurrentMatch().guessALetter(this.letterTextField.getText());
} catch (Exception ex) {
JOptionPane.showMessageDialog(this, "Please insert one letter only");
}}

public void guessALetter(String l) throws Exception {
DataPacket dp = new DataPacket();
Communicator c = new Communicator(p, session);
c.start();
}

public class Communicator extends Thread {

private Packet packet;
private Session session;

public Communicator(Packet p, Session s) {
this.session = s;
this.packet = p;
}

public void run() {
System.out.println("Communicator: "+Thread.currentThread());
Socket socket = session.getClientSocket();
ObjectOutputStream out = session.getOut();
ObjectInputStream in = session.getIn();

ResponsePacket reply;


try {

out.writeObject(this.packet);
out.flush();

reply = (ResponsePacket) in.readObject();
System.out.println("Received" + reply.getCurrentWordView() + reply.getCurrentWordView());

session.getCurrentMatch().setLastReply(reply);

session.getCurrentMatch().manageResponsePacket(reply);

} catch (ClassNotFoundException ex) {
Logger.getLogger(Communicator.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(Communicator.class.getName()).log(Level.SEVERE, null, ex);
}finally{

}}}

public void manageResponsePacket(ResponsePacket reply) {

this.setLastReply(reply);

if (reply.isGameMode()) {
setWordView(reply.getCurrentWordView());
setCounter(reply.getFailedAttemptsCounter());

setChanged();
notifyObservers(EventEnum.GAMERESPONSE);
} else if (reply.isGameOverMode()) {
}
}

如您所见,第二个线程是更新 GUI 的线程。

最佳答案

如果 manageResponsePacket() 更新 swing/awt GUI,则会遇到问题。您只能在 EDT 上更新 swing/awt GUI。使用 SwingUtilities.invokeLater() 通过 ResponsePacket 更新 GUI。

关于java - 我需要同步吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13139508/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com