native
-
先来看看源码(查看Thread 的·start方法源码)
可以看出源码调用了start0();方法;
而start0的定义在左后一行是这样的 private native void start0();
用到了native关键字
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();
首先了解JUI
JNI是Java Native Interface的缩写,通过使用 Java本地接口书写程序,可以确保代码在不同的平台上方便移植。 [1] 从Java1.1开始,JNI标准成为java平台的一部分,它允许Java代码和其他语言写的代码进行交互。JNI一开始是为了本地已编译语言,尤其是C和C++而设计的,但是它并不妨碍你使用其他编程语言,只要调用约定受支持就可以了。使用java与本地已编译的代码交互,通常会丧失平台可移植性。但是,有些情况下这样做是可以接受的,甚至是必须的。例如,使用一些旧的库,与硬件、操作系统进行交互,或者为了提高程序的性能。JNI标准至少要保证本地代码能工作在任何Java 虚拟机环境。
总结的来说: JUI就是扩展java的使用,融合不同的编程语言为Java所用,在最初的时候是为C和C++而设计的。
因为在最初java刚起步时,C++和C 才是主导,想要尽快站稳脚,必须要有调用c和c++的程序,于是他们就在内存中专门开辟了一块区,标记为Native代码。现在用到比较少,除非用java驱动硬件程序,比如打印机之类的。
何时调用
凡是使用native关键字的,说明java的作用范围打不到了,会去调用底层c语言的库。
所以在调用Thread的start方法时,java做不到创建线程的启动,然后通过调用本地方法接口JUI(JNI是Java Native Interface的缩写) 也就是 private native void start0()这个方法 (底层c语言的库)最终实现线程的启动。