java 线程执行原理,java线程在jvm中执行流程

java 线程执行原理,java线程在jvm中执行流程

从jvm视角看java线程执行过程

##首先thread.c注册jni函数

JNIEXPORT void JNICALL
Java_java_lang_Thread_registerNatives(JNIEnv *env, jclass cls)
{(*env)->RegisterNatives(env, cls, methods, ARRAY_LENGTH(methods));
}
static JNINativeMethod methods[] = {{"start0",           "()V",        (void *)&JVM_StartThread},{"stop0",            "(" OBJ ")V", (void *)&JVM_StopThread},{"isAlive",          "()Z",        (void *)&JVM_IsThreadAlive},{"suspend0",         "()V",        (void *)&JVM_SuspendThread},{"resume0",          "()V",        (void *)&JVM_ResumeThread},{"setPriority0",     "(I)V",       (void *)&JVM_SetThreadPriority},{"yield",            "()V",        (void *)&JVM_Yield},{"sleep",            "(J)V",       (void *)&JVM_Sleep},{"currentThread",    "()" THD,     (void *)&JVM_CurrentThread},{"countStackFrames", "()I",        (void *)&JVM_CountStackFrames},{"interrupt0",       "()V",        (void *)&JVM_Interrupt},{"isInterrupted",    "(Z)Z",       (void *)&JVM_IsInterrupted},{"holdsLock",        "(" OBJ ")Z", (void *)&JVM_HoldsLock},{"getThreads",        "()[" THD,   (void *)&JVM_GetAllThreads},{"dumpThreads",      "([" THD ")[[" STE, (void *)&JVM_DumpThreads},{"setNativeName",    "(" STR ")V", (void *)&JVM_SetNativeThreadName},
};

##java Thread.java类start0 调用jni native方法

private native void start0();

##start0 调用jvm.cpp执行JVM_StartThread方法

JVM_ENTRY(void, JVM_StartThread(JNIEnv* env, jobject jthread))JVMWrapper("JVM_StartThread");JavaThread *native_thread = NULL;// We cannot hold the Threads_lock when we throw an exception,// due to rank ordering issues. Example:  we might need to grab the// Heap_lock while we construct the exception.bool throw_illegal_thread_state = false;// We must release the Threads_lock before we can post a jvmti event// in Thread::start.{// Ensure that the C++ Thread and OSThread structures aren't freed before// we operate.MutexLocker mu(Threads_lock);// Since JDK 5 the java.lang.Thread threadStatus is used to prevent// re-starting an already started thread, so we should usually find// that the JavaThread is null. However for a JNI attached thread// there is a small window between the Thread object being created// (with its JavaThread set) and the update to its threadStatus, so we// have to check for thisif (java_lang_Thread::thread(JNIHandles::resolve_non_null(jthread)) != NULL) {throw_illegal_thread_state = true;} else {// We could also check the stillborn flag to see if this thread was already stopped, but// for historical reasons we let the thread detect that itself when it starts runningjlong size =java_lang_Thread::stackSize(JNIHandles::resolve_non_null(jthread));// Allocate the C++ Thread structure and create the native thread.  The// stack size retrieved from java is 64-bit signed, but the constructor takes// size_t (an unsigned type), which may be 32 or 64-bit depending on the platform.//  - Avoid truncating on 32-bit platforms if size is greater than UINT_MAX.//  - Avoid passing negative values which would result in really large stacks.NOT_LP64(if (size > SIZE_MAX) size = SIZE_MAX;)size_t sz = size > 0 ? (size_t) size : 0;native_thread = new JavaThread(&thread_entry, sz);// At this point it may be possible that no osthread was created for the// JavaThread due to lack of memory. Check for this situation and throw// an exception if necessary. Eventually we may want to change this so// that we only grab the lock if the thread was created successfully -// then we can also do this check and throw the exception in the// JavaThread constructor.if (native_thread->osthread() != NULL) {// Note: the current thread is not being used within "prepare".native_thread->prepare(jthread);}}}if (throw_illegal_thread_state) {THROW(vmSymbols::java_lang_IllegalThreadStateException());}assert(native_thread != NULL, "Starting null thread?");if (native_thread->osthread() == NULL) {ResourceMark rm(thread);log_warning(os, thread)("Failed to start the native thread for java.lang.Thread \"%s\"",JavaThread::name_for(JNIHandles::resolve_non_null(jthread)));// No one should hold a reference to the 'native_thread'.native_thread->smr_delete();if (JvmtiExport::should_post_resource_exhausted()) {JvmtiExport::post_resource_exhausted(JVMTI_RESOURCE_EXHAUSTED_OOM_ERROR | JVMTI_RESOURCE_EXHAUSTED_THREADS,os::native_thread_creation_failed_msg());}THROW_MSG(vmSymbols::java_lang_OutOfMemoryError(),os::native_thread_creation_failed_msg());}#if INCLUDE_JFRif (JfrRecorder::is_recording() && EventThreadStart::is_enabled() &&EventThreadStart::is_stacktrace_enabled()) {JfrThreadLocal* tl = native_thread->jfr_thread_local();// skip Thread.start() and Thread.start0()tl->set_cached_stack_trace_id(JfrStackTraceRepository::record(thread, 2));}
#endifThread::start(native_thread);JVM_END

##创建线程

native_thread = new JavaThread(&thread_entry, sz);

##系统调用创建线程 os::create_thread(this, thr_type, stack_sz);

ret = pthread_create(&tid, &attr, (void* (*)(void*)) thread_native_entry, thread);

JavaThread::JavaThread(ThreadFunction entry_point, size_t stack_sz) :Thread() {initialize();_jni_attach_state = _not_attaching_via_jni;set_entry_point(entry_point);// Create the native thread itself.// %note runtime_23os::ThreadType thr_type = os::java_thread;thr_type = entry_point == &compiler_thread_entry ? os::compiler_thread :os::java_thread;os::create_thread(this, thr_type, stack_sz);// The _osthread may be NULL here because we ran out of memory (too many threads active).// We need to throw and OutOfMemoryError - however we cannot do this here because the caller// may hold a lock and all locks must be unlocked before throwing the exception (throwing// the exception consists of creating the exception object & initializing it, initialization// will leave the VM via a JavaCall and then all locks must be unlocked).//// The thread is still suspended when we reach here. Thread must be explicit started// by creator! Furthermore, the thread must also explicitly be added to the Threads list// by calling Threads:add. The reason why this is not done here, is because the thread// object must be fully initialized (take a look at JVM_Start)
}
bool os::create_thread(Thread* thread, ThreadType thr_type,size_t req_stack_size) {assert(thread->osthread() == NULL, "caller responsible");// Allocate the OSThread object.OSThread* osthread = new OSThread(NULL, NULL);if (osthread == NULL) {return false;}// Set the correct thread state.osthread->set_thread_type(thr_type);// Initial state is ALLOCATED but not INITIALIZEDosthread->set_state(ALLOCATED);thread->set_osthread(osthread);// Init thread attributes.pthread_attr_t attr;pthread_attr_init(&attr);guarantee(pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED) == 0, "???");// Make sure we run in 1:1 kernel-user-thread mode.if (os::Aix::on_aix()) {guarantee(pthread_attr_setscope(&attr, PTHREAD_SCOPE_SYSTEM) == 0, "???");guarantee(pthread_attr_setinheritsched(&attr, PTHREAD_EXPLICIT_SCHED) == 0, "???");}// Start in suspended state, and in os::thread_start, wake the thread up.guarantee(pthread_attr_setsuspendstate_np(&attr, PTHREAD_CREATE_SUSPENDED_NP) == 0, "???");// Calculate stack size if it's not specified by caller.size_t stack_size = os::Posix::get_initial_stack_size(thr_type, req_stack_size);// JDK-8187028: It was observed that on some configurations (4K backed thread stacks)// the real thread stack size may be smaller than the requested stack size, by as much as 64K.// This very much looks like a pthread lib error. As a workaround, increase the stack size// by 64K for small thread stacks (arbitrarily choosen to be < 4MB)if (stack_size < 4096 * K) {stack_size += 64 * K;}// On Aix, pthread_attr_setstacksize fails with huge values and leaves the// thread size in attr unchanged. If this is the minimal stack size as set// by pthread_attr_init this leads to crashes after thread creation. E.g. the// guard pages might not fit on the tiny stack created.int ret = pthread_attr_setstacksize(&attr, stack_size);if (ret != 0) {log_warning(os, thread)("The %sthread stack size specified is invalid: " SIZE_FORMAT "k",(thr_type == compiler_thread) ? "compiler " : ((thr_type == java_thread) ? "" : "VM "),stack_size / K);thread->set_osthread(NULL);delete osthread;return false;}// Save some cycles and a page by disabling OS guard pages where we have our own// VM guard pages (in java threads). For other threads, keep system default guard// pages in place.if (thr_type == java_thread || thr_type == compiler_thread) {ret = pthread_attr_setguardsize(&attr, 0);}ResourceMark rm;pthread_t tid = 0;if (ret == 0) {int limit = 3;do {ret = pthread_create(&tid, &attr, (void* (*)(void*)) thread_native_entry, thread);} while (ret == EAGAIN && limit-- > 0);}if (ret == 0) {char buf[64];log_info(os, thread)("Thread \"%s\" started (pthread id: " UINTX_FORMAT ", attributes: %s). ",thread->name(), (uintx) tid, os::Posix::describe_pthread_attr(buf, sizeof(buf), &attr));} else {char buf[64];log_warning(os, thread)("Failed to start thread \"%s\" - pthread_create failed (%d=%s) for attributes: %s.",thread->name(), ret, os::errno_name(ret), os::Posix::describe_pthread_attr(buf, sizeof(buf), &attr));// Log some OS information which might explain why creating the thread failed.log_info(os, thread)("Number of threads approx. running in the VM: %d", Threads::number_of_threads());LogStream st(Log(os, thread)::info());os::Posix::print_rlimit_info(&st);os::print_memory_info(&st);}pthread_attr_destroy(&attr);if (ret != 0) {// Need to clean up stuff we've allocated so far.thread->set_osthread(NULL);delete osthread;return false;}// OSThread::thread_id is the pthread id.osthread->set_thread_id(tid);return true;
}

##通过函数回调thread_entry方法

native_thread = new JavaThread(&thread_entry, sz);

static void thread_entry(JavaThread* thread, TRAPS) {HandleMark hm(THREAD);Handle obj(THREAD, thread->threadObj());JavaValue result(T_VOID);JavaCalls::call_virtual(&result,obj,SystemDictionary::Thread_klass(),vmSymbols::run_method_name(),vmSymbols::void_method_signature(),THREAD);
}

##call_virtual 执行java run方法

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/839064.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

第八课,分支语句嵌套、随机数函数、初识while循环

一&#xff0c;分支结构的嵌套语法 在 Python 中&#xff0c;分支结构可以嵌套&#xff0c;这意味着你可以在一个条件语句中包含另一个条件语句。嵌套的分支结构可以让你更灵活地控制程序的逻辑流程。 怎么理解呢&#xff1f;打个比方&#xff1a;放学后&#xff0c;请三年级…

【MySQL精通之路】MySQL8.0新增功能-原子DDL语句支持

太长不看系列&#xff1a; 本文一句话总结&#xff0c;MySQL8.0支持多条DDL语句执行时的原子性了&#xff08;仅限Innodb&#xff09; 本文属于下面这篇博客的子博客&#xff1a; 【MySQL精通之路】MySQL8.0官方文档-新增功能 1.意义描述 MySQL 8.0支持原子数据定义语言&…

知乎广告推广开户最低需要多少钱?

精准高效的广告推广&#xff0c;是企业成功的关键&#xff0c;知乎作为知识分享与交流的高端平台&#xff0c;汇聚了大量高质量用户群体&#xff0c;无疑是品牌传播与产品推广的黄金之地。云衔科技作为您数字营销旅程中的得力伙伴&#xff0c;正以专业的知乎广告开户及代运营服…

快速搭建本地全文搜索

MeiliSearch 说起全文检索&#xff0c;在项目开发中&#xff0c;用的最多的就是 ElaticSearch 了&#xff0c;ElaticSearch 是基于 Apache Lucene 开发的全文检索服务&#xff0c;是一个端到端的解决方案&#xff0c;因此&#xff0c;部署和维护都非常复杂。今天介绍的这个全文…

AI配音可以商用吗?

随着人工智能技术的迅猛发展&#xff0c;AI配音技术在近几年的进步尤为显著。从最初的机械合成音到如今的智能语音合成&#xff0c;AI配音已经在广告、教育、媒体等领域中崭露头角&#xff0c;展现出其无限的潜力和广阔的应用空间。 AI配音技术的发展历程 AI配音技术起源于语…

如何在go项目中实现发送邮箱验证码、邮箱+验证码登录

前期准备 GoLand &#xff1a;2024.1.1 下载官网&#xff1a;https://www.jetbrains.com/zh-cn/go/download/other.html Postman&#xff1a; 下载官网&#xff1a;https://www.postman.com/downloads/ 效果图(使用Postman) Google&#xff1a; QQ&#xff1a; And …

【星海随笔】微信小程序(二)

WXML 模板语法 - 数据绑定 在data中定义页面的数据 在页面对应的 .js 文件中&#xff0c;把数据定义到 data 对象中即可&#xff1a; Page({data: {// 字符串类型的数据info: init data,// 数据类型的数据msgList: [{msg: hello},{msg: world}]} })Mustache 语法的格式 把 …

jQuery值操作例子 (代码)

直接上代码 <!DOCTYPE html> <html><head></head><body><div id"x1">例子</div><script src"js/jquery-3.7.1.min.js"></script><script>console.log($("#x1").text()) // 在浏览…

创建vue工程、Vue项目的目录结构、Vue项目-启动、API风格

环境准备 介绍&#xff1a;create-vue是Vue官方提供的最新的脚手架工具&#xff0c;用于快速生成一个工程化的Vue项目create-vue提供如下功能&#xff1a; 统一的目录结构 本地调试 热部署 单元测试 集成打包依赖环境&#xff1a;NodeJS 安装NodeJS 一、 创建vue工程 npm 类…

自定义横向思维导图,横向组织架构图,横向树图。可以自定义节点颜色,样式,还可以导出为图片

最近公司设计要求根据目录结构&#xff0c;横向展示。所以做了一个横向的思维导图&#xff0c;横向的树结构&#xff0c;横向的组织架构图&#xff0c;可以自定义节点颜色&#xff0c;样式&#xff0c;还可以导出为图片 话不多说&#xff0c;直接上图片&#xff0c;这个就是一…

使用redis优化纯真IP库访问

每次请求都需要加载10m的纯真IP qqwry.dat 文件&#xff0c;自己测试不会发现问题&#xff0c;但如果访问量上去了&#xff0c;会影响每次请求的相应效率&#xff0c;并且会消耗一定的io读写&#xff0c;故打算优化 优化方案 每个IP区间之间不存在交集&#xff0c;每个查找只要…

【已验证】debian12 更换国内源

1. 编辑 /etc/apt/sources.list 文件 sudo nano /etc/apt/sources.list2. 清空 sources.list 文件里的内容&#xff0c;讲下面内容拷贝到 sources.list deb http://mirrors.163.com/debian/ bookworm main contrib non-free non-free-firmware deb http://mirrors.163.com/de…

Nginx 代理与 Proxy 插件整合的最佳实践

推荐一个AI网站&#xff0c;免费使用豆包AI模型&#xff0c;快去白嫖&#x1f449;海鲸AI 写在前面 本文将介绍 Nginx 的正向代理配置以及如何与 Proxy 插件进行整合。正向代理是一种代理服务器&#xff0c;它代表客户端向目标服务器发送请求&#xff0c;并将响应返回给客户端…

【Linux】- HBase集群部署 [19]

简介 apache HBase是一种分布式、可扩展、支持海量数据存储的 NoSQL 数据库。 和Redis一样&#xff0c;HBase是一款KeyValue型存储的数据库。 不过和Redis涉及方向不同 Redis设计为少量数据&#xff0c;超快检索HBase设计为海量数据&#xff0c;快速检索 HBase在大数据邻域…

【python】python省市水资源数据分析可视化(源码+数据)【独一无二】

&#x1f449;博__主&#x1f448;&#xff1a;米码收割机 &#x1f449;技__能&#x1f448;&#xff1a;C/Python语言 &#x1f449;公众号&#x1f448;&#xff1a;测试开发自动化【获取源码商业合作】 &#x1f449;荣__誉&#x1f448;&#xff1a;阿里云博客专家博主、5…

2024年失业率狂飙18.1%,史上最难就业季即将来临,该如何逆袭?_2024年失业潮

【2024年被称为最难就业年&#xff0c;1158万大学生面临难题】 距离2024年毕业季还剩不到4个月&#xff0c;毕业学员将面临空前严峻的就业压力&#xff01;具国家统 计局的数据显示&#xff0c;1-2月份&#xff0c;16至24岁年轻人的失业率飙到18.1%&#xff0c;也就是说&…

JS之Reduce

reduce 是 JavaScript 中 Array 对象的一个方法&#xff0c;用于对数组中的每个元素执行一个提供的函数&#xff08;称为 reducer 函数&#xff09;&#xff0c;并将其结果汇总为单个返回值。它是一种高阶函数&#xff0c;可以用于数组的累积操作&#xff0c;例如求和、计算乘积…

微服务:利用RestTemplate实现远程调用

打算系统学习一下微服务知识&#xff0c;从今天开始记录。 远程调用 调用order接口&#xff0c;查询。 由于实现还未封装用户信息&#xff0c;所以为null。 下面我们来使用远程调用用户服务的接口&#xff0c;然后封装一下用户信息返回即可。 流程图 配置类中注入RestTe…

文心一言 VS 讯飞星火 VS chatgpt (265)-- 算法导论20.1 4题

四、假设不使用一棵叠加的度为 u \sqrt{u} u ​ 的树&#xff0c;而是使用一棵叠加的度为 u 1 k u^{\frac{1}{k}} uk1​的树&#xff0c;这里 k 是大于 1 的常数&#xff0c;则这样的一棵树的高度是多少&#xff1f;又每个操作将需要多长时间&#xff1f;如果要写代码&#xf…

模板中的右值引用(万能引用)、引用折叠与完美转发

模板中的右值引用&#xff08;万能引用&#xff09;、引用折叠与完美转发 文章目录 模板中的右值引用&#xff08;万能引用&#xff09;、引用折叠与完美转发一、万能引用与引用折叠1. 模板中的右值引用2. 自动类型推导(auto)与万能引用3. 引用折叠与万能引用4. lambda表达式捕…