這是我的java代碼的一部分,在這段代碼中有從0開始計數的標籤等,我想停止標籤來計算當我第一次點擊按鈕時,以及當我第二次點擊按鈕時,我想重新啓動標籤來重新計數,問題是當我第二次點擊按鈕時,標籤沒有重新啓動,因此請告訴我應該如何通知所有標籤以重新啓動數數???this.notifyAll();在java代碼中不起作用
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.SwingWorker;
public class Main implements ActionListener {
JButton button = new JButton("Click");
JFrame frame = new JFrame();
boolean wait=false;
public static void main(String arg[]) {
new Main();
}
public Main() {
frame.setLayout(new FlowLayout());
frame.getContentPane().setBackground(Color.BLACK);
frame.setExtendedState(JFrame.MAXIMIZED_BOTH);
button.addActionListener(this);
frame.add(button);
frame.setVisible(true);
new Producer().execute();
}
public class Producer extends SwingWorker<Void, Void> {
public Void doInBackground() {
for(int infinite=0; infinite!=-1; infinite++) {
new Counter().execute();
try {Thread.sleep(1000);} catch (InterruptedException e) {e.printStackTrace();}
}
return null;
}
}
public class Counter extends SwingWorker<Void, Void> {
JLabel label = new JLabel();
public Counter() {
label.setForeground(Color.WHITE);
frame.add(label);
}
public Void doInBackground() {
synchronized (this) {
for(int i=0; i!=-1; i++) {
if(wait==true)
try {this.wait();} catch(Exception exp) {exp.printStackTrace();}
label.setText(""+i);
try {Thread.sleep(200);} catch (InterruptedException e) {e.printStackTrace();}
}
}
return null;
}
}
public void actionPerformed(ActionEvent clicked) {
if(wait==false)
wait=true;
else if(wait==true) {
synchronized (this) {
this.notifyAll();
}
}
}
}
它看起來像'boolean wait = false'應該是'volatile'。 – Pshemo 2014-09-05 19:31:40
如果'wait'只在'synchronized'塊中被訪問(它真的應該是這樣),所以不需要它是volatile的。 – VGR 2014-09-05 19:36:59