[英]wait() and notify() and an ActionListener
我有一個使用兩個線程的圖形界面,每個線程必須在各自的文本區域中打印一個計數器。 第二個線程(名為threadEvent)與ActionListener和一個用於阻止和取消阻止該線程的按鈕一起使用。 當用戶按下按鈕時,它會阻塞threadEvent(它停止打印計數器),再次按下按鈕時,它將取消阻塞並繼續在相應的textArea中打印。 為此,我必須使用wait()阻塞線程,並使用notify()取消阻塞線程,我已經閱讀了一些有關此信息,但是我不知道如何通過按鈕使用它們
class T implements Runnable{
private boolean print = true;
private int i = 0;
private long pause;
private JTextArea textArea;
T(long miliseconds,JTextArea textAreax){
pause = miliseconds;
textArea = textAreax;
}
public void pressedButton()
{
if(print)
print = false;
else
print = true;
}
public void run()
{
while(print)
{
try
{
this.printCounter();
Thread.sleep(pause);
this.i++;
}
catch(InterruptedException e)
{
e.printStackTrace();
}
}
}
public void printCounter(){
String time;
time = Integer.toString(i);
textArea.setText(time);
}
}
class Interface extends JFrame implements ActionListener{
private JTextArea textArea,textArea2;
private JButton button;
private T thread,threadEvent;
private Thread t,tE;
Interface()
{
textArea = new JTextArea(10,7);
textArea2 = new JTextArea(10,7);
thread = new T(2000,textArea);
threadEvent = new T(1000,textArea2);
button = new JButton("Block/Unblock");
this.getContentPane().add(button,BorderLayout.SOUTH);
this.getContentPane().add(textArea,BorderLayout.WEST);
this.getContentPane().add(textArea2,BorderLayout.EAST);
t = new Thread(thread);
tE = new Thread(threadEvent);
t.start();
tE.start();
button.addActionListener(this);
}
public void actionPerformed(ActionEvent event)
{
threadEvent.pressedButton();
}
}
public class MessageThreads{
public static void main(String[] args) {
Interface i = new Interface();
i.setBounds(200, 200, 300, 240);
i.setVisible(true);
}
}
關於Swing和線程的注釋: Swing不是線程安全的 。 您只能從事件分配線程更新Swing組件(例如, textArea.setText(time);
)。
您可以使用SwingUtilities.invokeLater()
或SwingUtilities.invokeAndWait()
。 例如:
SwingUtilities.invokeLater( new Runnable() {
@Override
public void run()
{ `textArea.setText(time); }
});
PS。 我知道這更多是評論而不是答案,但是發布為評論太多了
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.