想请问一下,什么是原生方法(native methods)?可以举个列子吗?

在网上自己搜了一下,原生方法是依赖于平台的方法,同时不是以java语言实现,而是以更低级的语言,如C或C++,同时说在Class 类中定义的大部分方法均为原生方法,可以举个Class 类中的例子吗?

莫回无
浏览 871回答 1
1回答

Cats萌萌

jdk源码中有很多native方法,随手复制几个出来吧:public static native Thread currentThread();&nbsp; &nbsp; /**&nbsp; &nbsp; &nbsp;* A hint to the scheduler that the current thread is willing to yield&nbsp; &nbsp; &nbsp;* its current use of a processor. The scheduler is free to ignore this&nbsp; &nbsp; &nbsp;* hint.&nbsp; &nbsp; &nbsp;*&nbsp; &nbsp; &nbsp;* <p> Yield is a heuristic attempt to improve relative progression&nbsp; &nbsp; &nbsp;* between threads that would otherwise over-utilise a CPU. Its use&nbsp; &nbsp; &nbsp;* should be combined with detailed profiling and benchmarking to&nbsp; &nbsp; &nbsp;* ensure that it actually has the desired effect.&nbsp; &nbsp; &nbsp;*&nbsp; &nbsp; &nbsp;* <p> It is rarely appropriate to use this method. It may be useful&nbsp; &nbsp; &nbsp;* for debugging or testing purposes, where it may help to reproduce&nbsp; &nbsp; &nbsp;* bugs due to race conditions. It may also be useful when designing&nbsp; &nbsp; &nbsp;* concurrency control constructs such as the ones in the&nbsp; &nbsp; &nbsp;* {@link java.util.concurrent.locks} package.&nbsp; &nbsp; &nbsp;*/&nbsp; &nbsp; public static native void yield();&nbsp; &nbsp; /**&nbsp; &nbsp; &nbsp;* Causes the currently executing thread to sleep (temporarily cease&nbsp; &nbsp; &nbsp;* execution) for the specified number of milliseconds, subject to&nbsp; &nbsp; &nbsp;* the precision and accuracy of system timers and schedulers. The thread&nbsp; &nbsp; &nbsp;* does not lose ownership of any monitors.&nbsp; &nbsp; &nbsp;*&nbsp; &nbsp; &nbsp;* @param&nbsp; millis&nbsp; &nbsp; &nbsp;*&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;the length of time to sleep in milliseconds&nbsp; &nbsp; &nbsp;*&nbsp; &nbsp; &nbsp;* @throws&nbsp; IllegalArgumentException&nbsp; &nbsp; &nbsp;*&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if the value of {@code millis} is negative&nbsp; &nbsp; &nbsp;*&nbsp; &nbsp; &nbsp;* @throws&nbsp; InterruptedException&nbsp; &nbsp; &nbsp;*&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if any thread has interrupted the current thread. The&nbsp; &nbsp; &nbsp;*&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <i>interrupted status</i> of the current thread is&nbsp; &nbsp; &nbsp;*&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; cleared when this exception is thrown.&nbsp; &nbsp; &nbsp;*/&nbsp; &nbsp; public static native void sleep(long millis) throws InterruptedException;
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java