有人可以帮助我理解以下问题吗:-
- 新堆栈何时创建?执行
Thread t=new Thread()
或t.start()
start()
方法调用如何实现run()
?- 我们可以像JVM那样为每个线程分配内存吗?如果否,JVM 将如何修改正在运行的线程的堆栈内存。
最佳答案
来自 Thread 的 Javadoc :
A thread is a thread of execution in a program. The Java Virtual Machine allows an application to have multiple threads of execution running concurrently.
Every thread has a priority. Threads with higher priority are executed in preference to threads with lower priority. Each thread may or may not also be marked as a daemon. When code running in some thread creates a new Thread object, the new thread has its priority initially set equal to the priority of the creating thread, and is a daemon thread if and only if the creating thread is a daemon.
When a Java Virtual Machine starts up, there is usually a single non-daemon thread (which typically calls the method named main of some designated class). The Java Virtual Machine continues to execute threads until either of the following occurs:
- 已调用类 Runtime 的退出方法,并且安全管理器已允许进行退出操作。
- 所有非守护线程的线程都已死亡,原因是从对 run 方法的调用返回或抛出传播到 run 方法之外的异常。
现在,回答你的问题。
- 何时创建新堆栈?在执行 Thread t=new Thread() 或 t.start() 时?
构造函数创建一个新线程。它通过 start 方法运行。
- start() 方法调用如何实现 run()?
来自Thread的源代码:
public void run() {
if (target != null) {
target.run();
}
}
- 我们可以像JVM那样为每个线程分配内存吗?如果否,JVM 将如何修改正在运行的线程的堆栈内存。
不,您不能为每个线程分配内存。操作系统(Windows、Unix、OS X)控制线程的创建和销毁方式。 JVM 可以通过字符串标识符访问每个线程。
您可以阅读Thread source code有关 Thread 类的更多信息。
关于java - Thread类的start方法如何创建一个新的堆栈并执行run方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20185361/