【问题标题】:Java: Thread wont waitJava:线程不会等待
【发布时间】:2013-11-09 22:33:10
【问题描述】:

我一直试图让这个线程等待,但它不会等待或抛出异常或做任何事情......(我创建了一个新线程来运行线程,否则我的 gui 会由于调用 wait 方法而冻结编辑)

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;

public class Sandbox extends JFrame {

boolean paused = false;
Thread thread = new Thread() {
    public void run() {
        while(true) {
            System.out.println("running...");
        }
    }
};

private JButton button;
public Sandbox() throws Exception {
    thread.start();
    setSize(300, 150);
    setLocationRelativeTo(null);
    setDefaultCloseOperation(3);
    add(button = new JButton("Pause"));
    button.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
        new Thread() {
            public void run() {
                synchronized(thread) {  
                    try {
                        if(button.getText().equals("Pause")) {
                            thread.wait();
                            button.setText("Resume");

                        } else if(button.getText().equals("Resume")) {
                            thread.notify();
                            button.setText("Pause");
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        }.start();
    }});
    setVisible(true);
}

public static void main(String[] args) throws Exception {
    new Sandbox();
}
}

【问题讨论】:

  • 你不应该在 Thread 对象上调用 wait。使用join 等待它完成。 wait/notify 用于具有条件变量行为。
  • 我不认为线程会死掉......它在一个循环中无限期地继续
  • 我想你不明白wait 方法的作用。当您致电thread.wait() 时,您预计会发生什么?
  • 我希望线程停止打印“正在运行...”,并等到我调用 notify();
  • wait 只能停止调用此方法的线程,不能停止其他任何线程。你可能需要一些线程中断。

标签: java multithreading wait notify


【解决方案1】:

如果您要比较字符串,则需要使用equals() 而不是==

if(button.getText().equals("Pause")) {
    thread.wait();
    button.setText("Resume");

} else if(button.getText().equals("Resume")) {
    thread.notify();
    button.setText("Pause");
}

但是使用 wait 和 notify 可能不会真正做到你想要的。

【讨论】:

  • 是的,我明白,这只是粗略的代码来解决我已经处理了很长时间的问题。那么我还能用什么?
猜你喜欢
  • 1970-01-01
  • 2015-07-04
  • 1970-01-01
  • 2011-06-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多