调用Thread.start()时会发生什么 [英] What really happens when we Call Thread.start()

查看:231
本文介绍了调用Thread.start()时会发生什么的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

....正如问题的标题所说,我想知道当我们调用Thread.start()以及何时start方法返回和main resume执行时内部发生了什么。内部所有内容都被触发,比如使用调度程序等注册线程。?还有为什么使用执行程序?

....As the title of the questions says, I want to know what all things internally happen when we call Thread.start() and when does the start method return and main resume to execute. What all things internally get triggered like registering the thread with scheduler etc..? Also why executors are used ?

推荐答案

当你调用 t.start 时,JVM会创建一个新线程执行(具有自己的堆栈)。这是由本机代码完成的,它不是用Java完成的。那么JVM本身在新创建的执行线程中调用 t.run 。这通常是混淆源(对于初学者),因为Java类 Thread 与概念执行线程的名称相同。我想可以把这两个想象成:后者是'物理概念',前者是'抽象Java表示为类'

When you call t.start the JVM creates a new thread of execution (with its own stack). This is done by native code, it is not done in Java. So then the JVM itself calls t.run in the newly created thread of execution. This is usually a source of confusions (for starters) as the Java class Thread has the same name as the concept thread of execution. I guess one can think of these two as: the latter is the 'physical concept', the former is its 'abstract Java representation as a class'.

在当前执行线程中调用 t.start 和JVM调用之间通常需要一些时间新创建的执行线程中的 t.run ;因为创建一个新的执行线程是一个有点繁重的操作,所以有一段时间滞后。

It usually takes some time between you calling t.start in the current thread of execution, and the JVM calling t.run in the newly created thread of execution; there's some time lag there as creating a new thread of execution is a somewhat heavy operation.

Thread.start


导致该线程开始执行; Java虚拟机调用此线程的run方法。

Causes this thread to begin execution; the Java Virtual Machine calls the run method of this thread.

结果是两个线程同时运行:当前线程(从调用start方法返回) )和另一个线程(执行其run方法)。

The result is that two threads are running concurrently: the current thread (which returns from the call to the start method) and the other thread (which executes its run method).

多次启动一个线程永远不合法。特别是,一旦完成执行,线程可能无法重新启动。

It is never legal to start a thread more than once. In particular, a thread may not be restarted once it has completed execution.

这篇关于调用Thread.start()时会发生什么的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆