我对多线程程序执行期间的当前线程感到困惑。

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之前和之后启动多个线程:
  • 当您进入main方法内部时,无论何时调用Thread.currentThread()都会是“main-thread”?
  • 当您在AThread的run方法中时,无论何时调用Thread.currentThread()都会是“a-thread”?

  • 提前致谢。

    最佳答案



    因此,当您处于主方法中时,即您的主线程;而当您处于AThread的运行方法中时,则即您的a线程。

    关于java - Java当前线程,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/16697568/

    10-14 12:28