GUI (Swing)가있는 클라이언트 응용 프로그램을 작성하고 있습니다. 두 클래스 인 ClientClass와 MainFrame은 서로 다른 스레드를 실행 중이지만 서로 메서드를 호출해야합니다. ClientClass는 EventQueue 스레드 (displayGUI())의 응용 프로그램 수명주기 중 일부 지점에서 GUI (MainFrame)를 인스턴스화합니다. ClientClass는 recv()와 같이 MainFrame을 업데이트하는 클라이언트 클래스 thread에서 호출되는 많은 메소드를 포함합니다. 또한 MainFrame에는 ClientClass의 메서드를 호출하는 버튼을 누르는 것과 같은 이벤트에 의해 트리거되는 메서드가 있습니다. 이 예제에서 단추 누르기를 처리하는 애노 메서드가 EventQueue 스레드에 의해 호출되고 있다고 가정합니다.GUI 스레드간에 정보를 공유하는 방법은 무엇입니까?
저는 이런 종류의 응용 프로그램이 매우 일반적이며 다른 사람들의 통찰력을 좋아할 것이라고 확신합니다. 내가하는 일이 스레드로부터 안전하지 못하다는 느낌이 들었습니다. 그렇다면이 응용 프로그램의 현재 모델을 어떻게 수정하고 개선 할 수 있습니까?
예제 코드 :
MainFrame.java :
public MainFrame(ClientClass c) {
client = c;
// <Misc init code here>
btnSend = new JButton("Send");
btnSend.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent arg0) {
client.send("Hello!");
}
});
btnSend.setBounds(171, 120, 89, 23);
contentPane.add(btnSend);
}
public void updateElement() {
// Update of some element here, called from ClientClass
}
ClientClass.java :
private MainFrame mainFrame;
public ClientClass() {
}
public void displayGUI() {
final ClientClass c = this;
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
mainFrame = new MainFrame(c);
mainFrame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public void send(String msg) {
// Socket send operations here
// Currently called by the GUI's EventQueue thread?
}
public void recv() {
// Socket recv operations here
mainFrame.updateElement();
}
동시성에 대한 스윙 튜토리얼은 모든 질문에 답해야합니다. http://docs.oracle.com/javase/tutorial/uiswing/concurrency/ –