Java中线程的自定义实现:是否可以通过JNI? [英] Custom implementation of Thread in Java: Is it possible though JNI?

查看:83
本文介绍了Java中线程的自定义实现:是否可以通过JNI?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有可能以安全/正确的方式在Java中(使用JNI)实现自定义Thread类?

Would it be possible to implement a custom Thread class in Java (using JNI) in a safe / correct way?

假设我用一个本机的start()方法编写了自己的NewThread类,该方法分叉执行,在派生线程中调用run()并返回...

Suppose I write my own NewThread class, with a native start() method, which forks the execution, calls run() in the forked thread and returns...

有可能吗? JVM会抱怨吗?根据规格,它是否合法"?这样会破坏内存模型中的任何内容吗?它取决于特定的JVM吗?

Is that possible? Would the JVM complain? Is it "legal" according to the specs? Would this break anything, like, in the memory-model? Does it depend on the particular JVM?

推荐答案

Java本机接口 程序员指南和规范,第8.1.5节.

Your questions is answered in the Java Native Interface Programmer's Guide and Specification, section 8.1.5.

重要的问题是,VM必须使用与本机代码中相同的线程模型.由于操作系统本身不提供本机线程支持,因此某些最初的Java VM在某些操作系统(Linux)上使用了所谓的绿色线程"来模拟线程上下文切换.如果要在具有本机线程支持的较新的操作系统版本上使用这些旧VM之一,这些绿色线程"将无法与本机线程进行交互.

The important issue is that the VM has to use the same thread model as you are in your native code. Some of the first Java VMs used so called "green threads" on some operating systems (Linux) to emulate thread context switching, since the operating system itself didn't offer native threading support. These "green threads" would not be able to interact with native threads, if you would use one of these old VMs on a newer operating system version with native thread support.

从Sun的JRE 1.3开始,我认为所有普通" VM都直接使用本机线程,这意味着您可以在JNI代码中自己使用本机线程,并期望一切都能按预期工作.

Since Sun's JRE 1.3, I think all "normal" VMs are using native threads directly, which means that you can use native threads yourself in JNI code and expect everything to work as you expect.

这篇关于Java中线程的自定义实现:是否可以通过JNI?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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