jdk 中Runtime之单例模式 学习

本文通过一个简单的Java示例,展示了如何使用Runtime类获取当前运行时对象,并利用它来执行外部进程。通过比较不同方式获取的Runtime实例,证实了它们实际上是同一个对象。
这段代码是我从源码中截取的,大家很容易看到currentRuntime是一个静态变量,getRunTime对应的就是getInstacne。
不是说这种方法不好吗?



 1 public class Runtime {
 2 45     private static Runtime currentRuntime = new Runtime();
 3 
 4     
 5 Returns the runtime object associated with the current Java application. Most of the methods of class Runtime are instance methods and must be invoked with respect to the current runtime object.
 6 Returns:
 7 the Runtime object associated with the current Java application.
 8 54 
 9 55     public static Runtime getRuntime() {
10 56         return currentRuntime;
11 57     }
12 
13     

 

 1 package heelo;
 2 class ExecDemo { 
 3         public static void main(String args[]){ 
 4                 Runtime r = Runtime.getRuntime(); 
 5                 Runtime r1=Runtime.getRuntime();
 6                 if(r1==r)
 7                 {
 8                     System.out.println("他们是相同的");
 9                     
10                 }
11                 Process p = null; 
12                 try{ 
13                         p = r.exec("notepad"); //打卡一个记事本程序。你可以再cmd敲个notepad试试
14                 } catch (Exception e) { 
15                         System.out.println("Error executing notepad."); 
16                 } 
17         } 
18 } 

首先运行这代码,我们看到getRuntime获得的对象是相同的。同时exec可以执行其他进程。

 

 

 

 

 

转载于:https://www.cnblogs.com/hansongjiang/p/3813701.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值