在执行多线程程序时,我对当前线程是什么感到困惑。
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() 都会成为“主线程”?
- 当您在 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/