Java当前线程

标签 java multithreading

在执行多线程程序时,我对当前线程是什么感到困惑。

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. 当您在 main 方法中时,无论何时调用 Thread.currentThread() 都会成为“主线程”?
  2. 当您在 AThread 的 run 方法中时,无论何时调用 Thread.currentThread() 都会是“a-thread”?

提前致谢。

最佳答案

currentThread: Returns a reference to the currently executing thread object.

因此,当您在 main 方法中时,那是您的主线程,而当您在 AThread 的 run 方法中时,那是您的 a-thread。

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

相关文章:

java - 卡夫卡 : Manually producing record triggers exception in consumer

java - 什么是类似于 Rails 的面向对象桌面应用程序框架?

java - 在 AppEngine 上使用 Java Executor 导致 AccessControlException

java - 无法理解 Java 中的并发性,尝试阅读推荐书籍

java - 如何测试直接在外部 API 上运行的 Java 应用程序

java - 在Java中将Base64转换为二进制字符串

使用 Avro 工具将 JSON 转换为 Avro 后,java.io.IOException 不是数据文件

c++ - 具有订单保证的阻塞队列

python - 无法关闭Python应用程序

python - 当您丢失对 Python 线程的所有引用时会发生什么?