我目前正在大学里学习Java线程,今天的练习是创建两个线程。 线程A 打印从1到9没有睡眠的随机数,线程B 从1000到9999打50睡眠,这是一个无限循环直到我决定按下停止按钮这是一个中断两个线程的JButton。 事实上,我在尝试用一个按钮停止线程时遇到了一些麻烦,主要是试图找出如何解决它,以及如何为此目的创建一个actionEvent。
这是我到目前为止的代码:
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
public class RandomNumbers extends Thread {
long time;
long min;
long max;
private JFrame window;
private JButton stopButton;
public RandomNumbers(long min, long max, long time) {
this.min = min;
this.max = max;
this.time = time;
new Window();
}
public void run() {
try {
while (true) {
System.out.println((int) ((Math.random() * max) + min));
Thread.sleep(time);
}
} catch (Exception e) {
System.out.println("I was interrupted!");
}
}
public class Window {
public Window() {
window = new JFrame("Stop Button");
stopButton = new JButton("Stop");
stopButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
// ThreadA.interrupt(); //problem in here , what to do ? //****
// ThreadB.interrupt();
}
});
window.getContentPane().add(stopButton);
window.setSize(100, 100);
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setVisible(true);
}
}
public static void main(String[] args) throws InterruptedException {
Thread threadB = new RandomNumbers(1, 9, 50);
Thread threadA = new RandomNumbers(1000, 8999, 0);
threadB.start();
threadA.start();
}
}
此代码还有另一个问题,它会为每个线程创建 2个停止按钮,1,因为它不是构造函数。我有点失落所以我需要一些指导。 感谢任何帮助,非常感谢!
答案 0 :(得分:4)
您尚未将线程的实例传递到GUI中,而是为每个线程创建两个单独的 GUI,这有点怪异。将程序的各个部分分开,可能在不同的类中。例如:
e.g。 (只是GUI部分),
public class ThreadTest extends JPanel {
private JButton button = new JButton(new ButtonAction());
private MyRunnable[] runnables = {
new MyRunnable("thread 1", 1, 9, 50),
new MyRunnable("thread 2", 1000, 8999, 1) };
private Thread[] threads = new Thread[runnables.length];
public ThreadTest() {
add(button);
for (int i = 0; i < threads.length; i++) {
threads[i] = new Thread(runnables[i]);
threads[i].setName(runnables[i].getName());
threads[i].start();
}
}
private class ButtonAction extends AbstractAction {
public ButtonAction() {
super("Stop Threads");
}
@Override
public void actionPerformed(ActionEvent e) {
for (Thread thread : threads) {
if (thread != null && thread.isAlive()) {
thread.interrupt();
}
}
}
}
private static void createAndShowGui() {
JFrame frame = new JFrame("ThreadTest");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new ThreadTest());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}