EG。 - 上课
import java.awt.Color;
import java.util.Random;
import javax.swing.JLabel;
public class flashThread implements Runnable {
private JLabel temp;
Thread thread;
Color randColor;
public flashThread(JLabel toFlash) {
temp = toFlash;
thread = new Thread(this);
}
public void run() {
Random r = new Random();
while (true) {
temp.setForeground(new Color(r.nextInt(246) + 10,
r.nextInt(246) + 10, r.nextInt(246) + 10));
String tempString = temp.getText();
temp.setText("");
try {
thread.sleep(r.nextInt(500));
} catch (InterruptedException e) {
}
temp.setText(tempString);
try {
thread.sleep(r.nextInt(500));
} catch (InterruptedException e) {
}
}
}
public void begin() {
thread.start();
}
}
如果我在构造函数中添加了thread.start(),当我创建flashThread的两个对象时,只有其中一个闪烁。但是,如果我删除了那么,添加begin()方法,然后从初始化两个flashThread对象的类中调用begin方法,它们都闪烁。
任何帮助 - 我刚开始学习线程。
提前致谢! -Me
答案 0 :(得分:1)
首先请用大写字母开始你的类名,因为这是java中的惯例
如果在构造函数或方法中启动线程并不重要。一个问题是您访问Event Dispatching Thread(EDT)之外的UI元素,这是唯一允许访问UI元素的元素。
请改用SwingUtilities.invokeLater。此外,在类上调用静态方法,如Thread#sleep,例如Thread.sleep(1000);
不是实例。
因此,更新代码将如下所示:
public class FlashThread implements Runnable {
private JLabel temp;
Thread thread;
Color randColor;
public FlashThread(JLabel toFlash) {
temp = toFlash;
thread = new Thread(this);
thread.start();
}
public void run() {
final Random r = new Random();
while (true) {
SwingUtilities.invokeAndWait(new Runnable(){
public void run() {
// this will be executed in the EDT
temp.setForeground(new Color(r.nextInt(246) + 10,
r.nextInt(246) + 10, r.nextInt(246) + 10));
// don't perform long running tasks in the EDT or sleep
// this would lead to non-responding user interfaces
}
});
// Let our create thread sleep
try {
Thread.sleep(r.nextInt(500));
} catch (InterruptedException e) {
}
}
}
}
答案 1 :(得分:0)
如果在构造函数中调用新的Thread(this),则在完全创建对象之前传递对象的引用 - 因此它在任何时候都不能正常工作。