Runtime類理解
來源:程序員人生 發(fā)布時(shí)間:2015-08-17 09:12:27 閱讀次數(shù):3277次
Runtime類理解
雖然我們知道在編寫java程序時(shí),只有線程的概念,依托于JVM這個(gè)進(jìn)程,但是API提供了Runtime這個(gè)類,(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.)使得出現(xiàn)了子進(jìn)程,通過getRuntime.exec()可以用來履行shell腳本。原理就是:會(huì)從當(dāng)前虛擬機(jī)進(jìn)程fork1個(gè)子進(jìn)程,然后用新的進(jìn)程履行命令,而后退出。所以當(dāng)太多這類場景的時(shí)候會(huì)出現(xiàn)大量進(jìn)程,會(huì)成為問題,所以能用java API完成的就不要使用這類方式。理解:子進(jìn)程固然有管道的概念,所以明確了這1點(diǎn),就能夠從中得到InputStream/OutputStream進(jìn)行1些有用操作。
下面是1個(gè)簡單的示例:
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);
}
}
}
結(jié)果:

生活不易,碼農(nóng)辛苦
如果您覺得本網(wǎng)站對您的學(xué)習(xí)有所幫助,可以手機(jī)掃描二維碼進(jìn)行捐贈(zèng)