2012-10-30 182 views
0

我是否需要添加某種同步?我創建另一個線程來管理與服務器的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的一個。

+1

我只看到一個線程。 – jtahlborn

+0

的方法「guessALetter」,一個新的線程啓動 – wollow

+0

是的,這是一個我看。 – jtahlborn

回答

1

如果manageResponsePacket()更新擺動/ AWT GUI,你有問題。您只能更新EDT上的swing/awt GUI。使用SwingUtilities.invokeLater()用ResponsePacket更新GUI。

+0

好吧,我實際上使用觀察者模式,所以我只是從該方法調用notifyObservers。那是問題嗎? – wollow

+0

是notifyObservers同步還是異步? – jtahlborn

+0

我用的Java(執行和延長觀察的和觀察員)提供的一個,所以我不知道它是如何實現的。 – wollow