程序员人生 网站导航

Runtime类理解

栏目:php教程时间:2015-08-17 09:12:27
Runtime类理解


虽然我们知道在编写java程序时,只有线程的概念,依托于JVM这个进程,但是API提供了Runtime这个类,(Every Java application has a single instance of class Runtime that allows the application to interface with the environment in which the application is running. The current runtime can be obtained from the getRuntime method.An application cannot create its own instance of this class.)使得出现了子进程,通过getRuntime.exec()可以用来履行shell脚本。原理就是:会从当前虚拟机进程fork1个子进程,然后用新的进程履行命令,而后退出。所以当太多这类场景的时候会出现大量进程,会成为问题,所以能用java API完成的就不要使用这类方式。理解:子进程固然有管道的概念,所以明确了这1点,就能够从中得到InputStream/OutputStream进行1些有用操作。
下面是1个简单的示例:
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; //Executes the specified string command in a separate process. public class TestRuntime { public static void main(String[] args) throws IOException { Runtime r = Runtime.getRuntime(); Process p = r.exec("man ls"); System.out.println(p.isAlive()); BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream())); String res ; while((res = br.readLine()) != null){ System.out.println(res); } } }

结果:




------分隔线----------------------------
------分隔线----------------------------

最新技术推荐