【发布时间】:2020-09-20 18:07:06
【问题描述】:
为什么第一个例子不起作用?而第二个带线程的作品?而且我不明白睡眠有什么用。它是一个计数器,按下启动按钮后启动。如果我按下 INC-DEC 按钮,它必须改变计数器趋势。所以它增加或减少计数器。
没有线程的Contatore.java
public class Contatore extends JFrame {
private int count;
private boolean runFlag;
private JButton onOff;
private JButton start;
public Contatore() {
runFlag = true;
count = 0;
setLayout(new FlowLayout());
onOff = new JButton("INCR-DECR");
add(onOff);
onOff.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
runFlag = !runFlag;
}
});
start = new JButton("START");
add(start);
start.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
start.setEnabled(false);
while (true) {
try {
Thread.sleep(500);
} catch (InterruptedException e) {
System.out.println(e.getMessage());
}(runFlag) count++;
else count--;
System.out.println(count);
}
}
});
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
pack();
setVisible(true);
}
public static void main(String args[]) {
Contatore f = new Contatore();
}
}
带有线程的ContatoreRisolto.java
public class ContatoreRisolto extends JFrame {
private boolean runFlag;
private JButton onOff;
private JButton start;
public ContatoreRisolto() {
runFlag = true;
setLayout(new FlowLayout());
onOff = new JButton("INCR-DECR");
add(onOff);
onOff.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
runFlag = !runFlag;
}
});
start = new JButton("START");
add(start);
start.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
start.setEnabled(false);
Counter c = new Counter();
c.start();
}
});
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
pack();
setVisible(true);
}
public static void main(String args[]) {
ContatoreRisolto f = new ContatoreRisolto();
}
class Counter extends Thread {
public void run() {
int count = 0;
while (true) {
try {
Thread.sleep(500);
} catch (InterruptedException exc) {
System.out.println(e.getMessage());
}
if (runFlag) count++;
else count--;
System.out.println(count);
}
}
}
}
【问题讨论】:
标签: java multithreading user-interface button listener