我正在用附带的GUI(Swing)编写客户端应用程序。我的两个类ClientClass和MainFrame运行不同的线程,但需要相互调用方法。 ClientClass在EventQueue线程(displayGUI())的应用程序生命周期中的某个时间点实例化GUI(MainFrame)。 ClientClass包含许多方法,如recv(),从客户端类线程调用,更新MainFrame。反过来,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();
}
有关并发性的swing教程应该回答您所有的问题:http://docs.oracle.com/javase/tutorial/uiswing/concurrency/ –