現在、多数のボタンを含む Swing-Interface を備えた小さなアプリケーションを作成しています。今私の問題は次のとおりです。アプリケーションを起動した後、2 つのボタンが押されるのを待ってから通常どおりに処理するメソッドが呼び出されます。2 つのスレッドがあります。1 つはメイン スレッドで、もう 1 つは 2 つのボタンが押されるまで待機するためだけに作成されます。ボタンについては、変数を 1 ずつ増やし、変数が 2 のときにもう一方の変数を起動するメソッドを呼び出す、いつものように ActionListener を追加しました。
だからここに私のコードがあります:
int counter = 0;
static Thread thread1;
static Thread thread2;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
thread1 = new Thread() {
@Override
public void run() {
MainFrame frame = new MainFrame();
frame.setVisible(true);
start();
}
};
thread1.start();
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public MainFrame() {
//other stuff and similar Listeners
JButton button1 = new JButton();
button1.addActionListener(new ActionAdapter() {
@Override
public void actionPerformed(ActionEvent ae) {
count++;
notifyIfTwo();
}
});
}
public void notifyIfTwo() {
if (count == 2) {
synchronized(thread2) {
notifyAll();
}
}
}
public void start() {
thread2 = new Thread() {
@Override
public void run() {
try {
synchronized(thread1) {
thread2.wait();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
thread2.start();
//other stuff
}
どうやっても、私はいつも IllegalMonitorStateException を受け取ります。カウンターがまだ2かどうかを確認するthread2内のループでも試しましたが、同じ結果が得られました。同期の問題と関係があると思いますが、私はマルチスレッド全体に慣れていないので、正しい方向への指針を教えていただければ幸いです。
それとも、「2 つのボタンが押されるまで待つ」という問題全体を行う簡単な方法を知っているでしょうか?
よろしくお願いし
ます。