程序中只有四行注释,源程序是没有那四行注释的,也就是用一个线程来执行edt.incrementLabel()的方法。但我把线程去了,只用循环,为什么程序运行的就和以前不一样了呢?我线程学的不好,谁能告诉我下
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class SwingThreading extends JFrame implements ActionListener {
private JLabel counter;
private int tickCounter = 0;
private static SwingThreading edt;
public SwingThreading() {
super("Swing Threading");
JButton freezer = new JButton("Increment");
freezer.addActionListener(this);
counter = new JLabel("0");
add(freezer, BorderLayout.CENTER);
add(counter, BorderLayout.SOUTH);
pack();
setLocationRelativeTo(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
public void actionPerformed(ActionEvent e) {
incrementLabel();
}
private void incrementLabel() {
tickCounter++;
Runnable code = new Runnable() {
public void run() {
counter.setText(String.valueOf(tickCounter));
}
};
if (SwingUtilities.isEventDispatchThread()) {
code.run();
} else {
SwingUtilities.invokeLater(code);
}
}
public static void main(String... args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
edt = new SwingThreading();
edt.setVisible(true);
// new Thread(new Runnable() {
// public void run() {
while (true) {
try {
Thread.sleep(300);
} catch (InterruptedException e) {
}
edt.incrementLabel();
}
// }
// }).start();
}
});
}
}
是不是注释了之后就什么都没显示?SwingUtilities.invokeLater这个是SWING的执行机制的线程,如果不新建立个线成 直接在SwingUtilities.invokeLater里sleep()的话 就相当与停止了该线程 要注意edt = new SwingThreading();
edt.setVisible(true);
可是在SwingUtilities这个线程里的,也就是说,绘画出按纽和文本域是在SwingUtilities执行的,所以该线成要是sleep的话 就绘画不出来了 在swing编程中的sleep()通常都不在SwingUtilities进行
线程就是并发的基础
自己先去看看线程的概念和例子吧
http://www.javaresearch.org/article/75478.htm
http://developer.51cto.com/art/200906/130139.htm
注释掉之后不运行 是因为让一个线程开始的方法 是调用该线程的start方法,也就是说 你把.start()注释掉了 它就运行不了了啊。
楼主是不是注释错行了 现在程序是死循环啊。