这个问题的意思是,如果我有一个运行某些代码的线程,并且该代码使用了一个不在线程中的方法,那么该方法是否也在同一个线程中运行。这是我正在谈论的代码示例。这是一个使用 android 的示例,但我猜这同样适用于 java。
new Thread(new Runnable() {
@Override
public void run() {
//Logic
randomMethod();
}
}).start();
然后是随机方法:
public void randomMethod()
{
//This method is not wrapped in a thread.
}
那么 randomMethod() 是与调用它的线程一起运行还是单独的线程?
最佳答案
方法在调用者的上下文中运行。您可以随时使用 Thread#currentThread()
检查您的线程 ID , 例如
// How to get the current thread id and name
Thread t = Thread.currentThread();
System.out.printf("Thread: %d - %s%n", t.getId(), t.getName());
注意:常规 Java 应用程序在 main
线程(id 为“1”)上启动。
关于java - 方法是否包含在线程中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24521321/