java - 在构造函数和方法中调用 thread.start() 方法有什么区别

标签 java multithreading constructor

例如。 - 上课

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/

相关文章:

vb.net - 在模拟用户下运行的非 UI 线程是否会自动模拟 UI 线程?

multithreading - Python 多处理队列慢

java - 如何使用 DES 在 Java 中加密数据并将该数据解密为 Object-c

java - 当 concurrencyLevel 大于 ConcurrentHashMap 的容量时会发生什么?

c# - 更改线程优先级 - Unity 3d

Java - 重写在构造函数中创建的对象?

Java : recursive constructor call and stackoverflow error

c++ - 当我们有设置值的 setter 时,为什么我们要使用参数化构造函数

java - 查找排序数组中整数出现的边界的问题 (Java)

java - 无法启动 Activity ComponentInfo - 更改为 setContentView()