1

このスレッドを待機させようとしましたが、待機したり、例外をスローしたり、何もしません... (スレッドを実行するために新しいスレッドを作成しました。

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();
}
}
4

1 に答える 1

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 を使用しても、実際には期待どおりの結果が得られない可能性があります。

于 2013-11-09T22:35:41.283 に答える