我改變了代碼,以更詳細的版本,所以你可以得到我的問題的一個更好的主意。有效地監控int值
我需要「看」一個整數值,並立即向它的變化時作出反應。到目前爲止,我發現的最好方法是在無限循環中使用線程。
以下是我的項目大大簡化了一部分。總而言之,通過點擊我的Bubble類中的按鈕,notificationValue被設置爲1。我需要小程序能夠監視此通知值,並在其發生更改時作出響應。
這裏是我的小程序:
public class MyApplet extends JApplet
{
Bubble myBubble = new Bubble();
public void run()
{
new Thread(
new Runnable() {
public void run() {
while(true) {
if(myBubble.getNotificationValue() == 1) {
/* here I would respond to when the
notification is of type 1 */
myBubble.resetNotificationValue;
}
else if(myBubble.getNotificationValue() == 2) {
/* here I would respond to when the
notification is of type 2 */
myBubble.resetNotificationValue;
}
else if(myBubble.getNotificationValue() != 2) {
/* if it is any other number other
than 0 */
myBubble.resetNotificationValue;
}
// don't do anything if it is 0
}
}
}).start();
}
}
這裏是我的課:
public class Bubble extends JPanel
{
public JButton bubbleButton;
public int notificationValue = 0;
public int getNotificationValue()
{
return notificationValue;
}
public void resetNotificationValue()
{
notificationValue = 0;
}
protected void bubbleButtonClicked(int buttonIndex)
{
notificationValue = buttonIndex;
}
public Bubble()
{
bubbleButton = new JButton();
bubbleButton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent event)
{
bubbleButtonClicked(1);
}
});
}
}
但很明顯,保持了CPU高達100%,是效率不高的。什麼是更好的方法來做到這一點? (假設我不能改變任何負責改變整數的方法。)
通常你會使用帶有脈衝的鎖來通知改變,所以等待的線程會喚醒,但是這需要一個對象鎖定並且能夠修改setter。但是這聽起來像你不能將注入功能注入setter? – AaronLS
然而,你在你的線程中解決了這個邏輯問題 - 不要忘記訪問已實現的Swing組件的_any_屬性_必須在EDT – kleopatra