0

例如。- 上课

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 方法,它们都闪烁。

任何帮助 - 我才刚刚开始了解线程。

提前致谢!-我

4

2 回答 2

1

首先,请以大写字母开头您的类名,因为这是 java 中的约定。
在构造函数或方法中启动线程并不重要。一个问题是您在事件调度线程(EDT) 之外访问 UI 元素,这是唯一允许访问 UI 元素的线程。
请改用SwingUtilities.invokeLater。此外,在类上调用静态方法,如Thread#sleepThread.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) {
        }
    }
  }
}
于 2012-07-03T23:48:13.027 回答
0

如果您在构造函数中调用 new Thread(this) ,则您将在对象完全创建之前传递对它的引用 - 因此它不应始终正常工作。

于 2012-07-03T23:43:43.603 回答