我正在用附帶的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/ –