引出场景,创建一个线程并使其就绪
public class Test {
public static void main(String[] args) {
Thread thread = new Thread();
thread.start();
}
}
按住crlt进入Thread类查看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();
在该方法中,先判断线程是不是新生的,然后去执行start0(),start0()是在类中定义的一个像接口一样的方法,平时我们见到的这类方法都是在接口或抽象类中。
接下来回到创建线程的Test类,写一个类似接口的方法
注意到,在Thread类的start0()方法是被native修饰的,我们给hello()方法也加上native关键字,会发现报红消失
那么native关键字到底起了什么作用,下面来进行讲解
带有native关键字的方法,说明java的作用范围达不到的,需要去调用底层C语言的库。
执行被native修饰的方法时,native会进入本地方法栈,调用本地方法接口JNI(Java Native Interface)
JNI是为了扩展java的使用,融合不同的编程语言为java所用
历史:
在java刚刚诞生的时候C语言和C++横行,java想要立足,就必须调用C语言和C++的程序,它在内存区域专门开辟了一块标记区域Native Method Stack(本地方法栈),登记native方法
native的使用场景:
java驱动打印机;java管理系统;一般需要调用到硬件时需要native方法