Version: Next

Native关键字

新建一个线程,进入start()方法的源码

public class Demo01 {
public static void main(String[] args) {
new Thread(()->{
},"my thread name").start();
}
}
public synchronized void start() {
/**
* This method is not invoked for the main method thread or "system"
* group threads created/set up by the VM. Any new functionality added
* to this method in the future may have to also be added to the VM.
*
* A zero status value corresponds to state "NEW".
*/
if (threadStatus != 0)
throw new IllegalThreadStateException();
/* Notify the group that this thread is about to be started
* so that it can be added to the group's list of threads
* and the group's unstarted count can be decremented. */
group.add(this);
boolean started = false;
try {
start0();
started = true;
} finally {
try {
if (!started) {
group.threadStartFailed(this);
}
} catch (Throwable ignore) {
/* do nothing. If start0 threw a Throwable then
it will be passed up the call stack */
}
}
}
private native void start0(); // 一个用native修饰的方法,像个接口方法一样,很诡异
注意

凡是带了native关键字的,表示Java的作用范围无法到达,去调用底层C语言的库

JNI Java Native Interface Java本地方法接口

凡是带了native关键字的方法,都会进入本地方法栈

Native Method Stack 本地方法栈

本地接口的作用是融合不同的编程语言为Java所用,它的初衷是融合C/C++程序,Java在诞生的时候还是C/C++横行的时代,想要立足,必须有调用C/C++程序的能力,于是就在内存中专门开辟了一块区域处理标记为native的代码。

他的具体做法是,在Native Method Stack中登记native方法,在执行引擎Execution Engine执行的时候加载Native Libraries

目前该方法使用的越来越少了,除非是与硬件有关的应用,比如通过Java程序驱动打印机或者Java系统管理生产设备,在企业级应用中已经比较少见