##0预备知识
Runtime类是一个与JVM运行时环境有关的Singleton类,有以下几个值得注意的地方:
0.1 Runtime.getRuntime()可以取得当前JVM的运行时环境,这也是在Java中唯一得到运行时环境的方法。
0.2 Runtime上其他大部分的方法都是实例方法,也就是说每次进行运行时调用时都要用到getRuntime
方法。
0.3 Runtime中的exit方法是退出当前JVM的方法,估计也是唯一的。System类中的exit实际上也是通过调用Runtime.exit()来退出JVM的。
Java对Runtime返回值的一般规则,0代表正常退出,非0代表异常中止,这只是Java的规则,在各个操作系统中总会发生一些小的混淆。
0.4 Runtime.addShutdownHook()方法可以注册一个hook在JVM执行shutdown的过程中,方法的参数只要是一个初始化过但是没有执行的Thread实例就可以。(注意,Java中的Thread都是执行过了就不值钱的哦)
0.5说到addShutdownHook这个方法就要说一下JVM运行环境是在什么情况下shutdown或者abort的。
Shutdown:当最后一个非精灵进程退出或者收到了一个用户中断信号、用户登出、系统shutdown、Runtime的exit方法被调用时JVM会启动shutdown的过程,在这个过程开始后,他会并行启动所有登记的shutdown hook(注意是并行启动,这就需要线程安全和防止死锁)。当shutdown过程启动后,只有通过调用halt方法才能中止shutdown的过程并退出JVM。
Abort: abort退出时JVM就是停止运行但并不一定进行shutdown。这只有JVM在遇到SIGKILL信号或者windows中止进程的信号、本地方法发生类似于访问非法地址一类的内部错误时会出现。这种情况下并不能保证shutdown hook是否被执行。
0.6 Runtime.exec()方法的所有重载。这里要注意的是:
public Process exec(String[] cmdarray, String[] envp, File dir);
这个方法中cmdArray是一个执行的命令和参数的字符串数组,数组的第一个元素是要执行的命令往后依次都是命令的参数,envp中是name=value形式的环境变量设置,如果子进程要继承当前进程的环境时是null。
'启动线程池时候调用 线程数量为CPU的数量'
ExecutorService mExecutorService = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());
http://jiangshuiy.iteye.com/blog/1674235
http://outofmemory.cn/code-snippet/2253/java-usage-Runtime-availableProcessors-get-keyong-chuliqi-geshu
要显示java虚拟机可用的处理器个数,可以通过Runtime类的availableProcessors()方法得到。
要获得Runtime类的实例,需要调用其静态方法getRuntime(),如下例所示:
/**
* Main.java
*
*@authoroutofmemory.cn
*/
publicclassMain{
/**
* Displays the number of processors available in the Java Virtual Machine
*/
'publicvoiddisplayAvailableProcessors(){'
''Runtimeruntime=Runtime.getRuntime();''
"intnrOfProcessors=runtime.availableProcessors();"
System.out.println("Number of processors available to the Java Virtual Machine: "+nrOfProcessors);
}'
/**
* Starts the program
*@paramargs the command line arguments
*/
publicstaticvoidmain(String[]args){
newMain().displayAvailableProcessors();
}
}
网友评论