gpt4 book ai didi

java - 程序在调用 wait() 时停止;在java中

转载 作者:行者123 更新时间:2023-12-02 05:39:19 24 4
gpt4 key购买 nike

我已同步此代码以使用等待和通知,但现在当我通过单击等待按钮调用 wait() 时,程序停止执行(程序挂起)。请帮忙,不要建议我使用不同的链接,请修复此代码并回答。

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;


public class Main extends JFrame implements ActionListener, Runnable {


JLabel time = new JLabel();
JButton wait = new JButton("wait");
JButton notify = new JButton("notify");
Thread count = new Thread(this);
int sec=0;


public static void main(String arg[]) {
new Main();
}


public Main() {
super("Counter");
setSize(250,100);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLayout(new FlowLayout());
setVisible(true);
add(time);
add(wait);
add(notify);
notify.setEnabled(false);
wait.addActionListener(this);
notify.addActionListener(this);
count.start();
}


public void actionPerformed(ActionEvent e) {

synchronized(count) {
if(e.getSource()==wait) {
try
{
count.wait();
wait.setEnabled(false);
notify.setEnabled(true);
}
catch (Exception e1) {
e1.printStackTrace();
}
}

else if(e.getSource()==notify) {
count.notify();
wait.setEnabled(true);
notify.setEnabled(false);
}

}
}



public void run() {

synchronized (this) {
while(true) {
time.setText(String.format("seconds=%d",sec));
try
{
Thread.sleep(1000);
}
catch (InterruptedException e) {
e.printStackTrace();
}
sec++;
}
}
}
}

最佳答案

当您调用 wait() 时,您将阻塞 EDT。当您尝试 notify() 时,它将不起作用,因为负责按钮事件 (EDT) 的线程已经在等待。您必须在不同的线程上调用 notify()

public void actionPerformed(ActionEvent e) {
synchronized(count) {
if(e.getSource()==wait) {
try
{
count.wait(); // start blocking this thread
wait.setEnabled(false); // im pretty sure this doesnt get called until notified either
notify.setEnabled(true);
}
catch (Exception e1) {
e1.printStackTrace();
}
} else if(e.getSource()==notify) {
count.notify(); // will never get called cause this thread is blocked, waiting to be notified by another thread
wait.setEnabled(true);
notify.setEnabled(false);
}

}
}

关于java - 程序在调用 wait() 时停止;在java中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24642597/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com