Runtime類理解

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腳本。原理就是:會從當前虛擬機進程fork一個子進程,然後用新的進程執行命令,而後退出。所以當太多這種場景的時候會出現大量進程,會成爲問題,所以能用java API完成的就不要使用這種方式。理解:子進程當然有管道的概念,所以明確了這一點,就可以從中得到InputStream/OutputStream進行一些有用操作。
下面是一個簡單的示例:
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());// JDK 1.8新增
		BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));
		String res ;
		while((res = br.readLine()) != null){
			System.out.println(res);
		}
	}
}

結果:




發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章