java - Thread类的start方法如何创建一个新的堆栈并执行run方法

标签 java multithreading

有人可以帮助我理解以下问题吗:-

  1. 新堆栈何时创建?执行 Thread t=new Thread()t.start()
  2. start()方法调用如何实现run()
  3. 我们可以像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:

  1. 已调用类 Runtime 的退出方法,并且安全管理器已允许进行退出操作。
  2. 所有非守护线程的线程都已死亡,原因是从对 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/

相关文章:

sql - Rails/SQL 如何让不同的工作人员处理不同的记录?

java - 目标运行时 WildFly 在 maven 测试后解包

java - java中延迟后调用特定函数

java - 在新线程中打开 Eclipse Wizard 或 Eclipse MessageDialog

linux - Linux 和 Windows 中的多线程模型

c# - 如何等待 BackgroundWorker 取消?

java - 如何避免在 HttpServletRequest 中过滤文件名

java - 为什么 jOOQ 建议将生成的代码放在 "/target"下而不是 "/src"下?

javascript - 使用 IF block 后 JSP Servlet 不工作

java - SoapUI 无法正确打印多字节字符