Native关键字

引出场景,创建一个线程并使其就绪

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方法

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值