例如。 - 上课
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的两个对象时,只有其中一个闪烁。但是,如果我删除 then,添加 begin() 方法,然后从初始化两个 flashThread 对象的类中调用 begin 方法,它们都会闪烁。
任何帮助 - 我才刚刚开始了解线程。
提前致谢! -我
最佳答案
首先请以大写字母开头,因为这是 java 中的约定。
无论您是在构造函数中还是在方法中启动线程都没有关系。一个问题是您访问 Event Dispatching Thread 之外的 UI 元素。 (EDT),这是唯一允许访问 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) {
}
}
}
}
关于java - 在构造函数和方法中调用 thread.start() 方法有什么区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11320619/