在执行多线程程序期间,我对当前线程是什么感到困惑。
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”?
提前致谢。