例如。- 上课
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 方法,它们都闪烁。
任何帮助 - 我才刚刚开始了解线程。
提前致谢!-我