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);
		}
	}
}

结果:




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值