1
我目前在我的大学里有关于Java线程的课程,今天的练习是关于创建两个线程。 线程A打印随机数从1到9,没有睡眠,并线程B从1000到9999与50睡眠,这是一个无限循环直到我决定按停止按钮这是一个JButton该中断两个线程。 事情是,我在尝试用一个按钮停止线程时遇到了一些麻烦,主要是试图找出如何解决这个问题,以及如何为此创建一个actionEvent。用JButton中断线程
这是我到目前为止的代码:
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为每个线程的另一个问题,因为它没有构造..我有点失落,所以我需要一些指导。 任何帮助表示赞赏,非常感谢!
您创建两个线程,并且每个线程创建一个窗口。所以那会给你两扇窗户。此外,调试它将很好地知道当前线程的名称:''System.out.println(Thread.currentThread()。getName()+“:”+(int)((Math.random()* max) +分钟));' – flup