1

マルチスレッド プログラムの実行中に現在のスレッドが何であるかについて混乱しています。

public class CurrentThread {

public static void main(String[] args) {
            // FROM HERE: will always be "main-thread" the current thread ?
    CurrentThread currentThread = new CurrentThread();
    currentThread.testCurrentThread();
            // TO HERE         
}

private void testCurrentThread() {
    // some other threads starts...
    AThread athread = new AThread();
    athread.start();
    // some other threads starts...
}

class AThread extends Thread {

    public AThread() {
        setName("thread-a");
    }

    public void run() {
        // FROM HERE: will always be thread-a the current thread during finish the run method ?
                    // some process
                    // TO HERE...
    }
}

}

スレッド AThread の開始前後に複数のスレッドを起動するとします。

  1. メイン メソッド内にいる場合、Thread.currentThread() を呼び出すたびに「メイン スレッド」になりますか?
  2. AThread の run メソッド内にいる場合、Thread.currentThread() を呼び出すたびに「a-thread」になりますか?

前もって感謝します。

4

2 に答える 2

5

currentThread: 現在実行中のスレッド オブジェクトへの参照を返します。

したがって、メイン メソッドにいるとき、それがメイン スレッドであり、AThread の実行メソッドにいるとき、それが a-thread です。

于 2013-05-22T17:03:41.243 に答える