코드를 훨씬 더 자세한 버전으로 변경하여 더 나은 아이디어를 얻을 수 있습니다.효율적으로 int 값을 모니터하십시오.
정수 값을 "감시"하고 변경 될 때 즉시 응답해야합니다. 지금까지 내가 찾은 가장 좋은 방법은 스레드를 무한 루프에서 사용하는 것입니다.
다음은 내 프로젝트에서 매우 단순화 된 부분입니다. 요약하면 notificationValue는 My Bubble 클래스 내의 버튼 클릭으로 1로 설정됩니다. 이 notificationValue를 모니터하고 변경 될 때마다 응답 할 수 있으려면 애플릿이 필요합니다. 여기
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);
}
});
}
}
는하지만 분명히 그 100 %의 CPU를 유지하고 전혀 효율적이지
여기 내 애플릿입니다. 이것을하는 더 좋은 방법은 무엇입니까? (정수를 변경하는 메소드를 변경할 수 없다고 가정하십시오.)
일반적으로 변경 사항을 알리기 위해 펄스가있는 잠금 장치를 사용하므로 스레드 대기 상태가 유지되지만 개체를 잠그고 설정기를 수정할 수 있어야합니다. 그러나 당신이 세터에 기능을 주입 할 수없는 것 같은데? – AaronLS
그러나 스레드에서 논리 문제를 해결하십시오. 실현 된 Swing 구성 요소의 _any_ 속성에 액세스하는 것이 _ EDT – kleopatra