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のオブジェクトを2つ作成すると、そのうちの1つだけが点滅します。ただし、削除した場合は、begin()メソッドを追加してから、両方のflashThreadオブジェクトを初期化したクラスからbeginメソッドを呼び出すと、両方がフラッシュします。

ヘルプ-スレッドについて学び始めたばかりです。

前もって感謝します!-自分

4

2 に答える 2

1

これはJavaの慣例であるため、まず、クラス名は大文字で始めてください。
コンストラクターでスレッドを開始するか、メソッドでスレッドを開始するかは関係ありません。1つの問題は、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) {
        }
    }
  }
}
于 2012-07-03T23:48:13.027 に答える
0

コンストラクターでnewThread(this)を呼び出すと、オブジェクトが完全に作成される前にオブジェクトへの参照が渡されるため、常に正しく機能するとは限りません。

于 2012-07-03T23:43:43.603 に答える