栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

System 类 和 Runtime 类的常用用法介绍

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

System 类 和 Runtime 类的常用用法介绍

System类的常用用法
1,主要获取系统的环境变量信息
复制代码 代码如下:
public static void sysProp()throws Exception{
  Map env = System.getenv();
  //获取系统的所有环境变量
  for(String name : env.keySet()){
   System.out.println(name + " : " +env.get(name));
  }
  //获取系统的指定环境变量的值
  System.out.println(env.get("JAVA_HOME"));

  //获取系统的所有属性
  Properties prop = System.getProperties();
  //将系统的属性保存到配置文件中去
  prop.store(new FileOutputStream("Prop.properties"),"System properties");
  //输出特定的系统属性
  System.out.println(System.getProperty("os.name"));
 }

2,与系统时间有关的方法操作
复制代码 代码如下:
public static void sysTime(){
  //获取系统当前的时间毫秒currentTimeMillis()(返回当前时刻距离UTC 1970.1.1 00:00的时间差)
  Long time = System.currentTimeMillis();
  System.out.println(time);

  Long time1 = System.nanoTime();//主要用于计算时间差单位纳秒
  Long time3 = System.currentTimeMillis();
  for(Long i =0l ;i <999l; i++){}
  Long time2 = System.nanoTime();
  Long time4 = System.currentTimeMillis();
  System.out.println(time2 - time1+ " : " +(time4 - time3));
 }

3,鉴别两个对象在堆内存当中是否是同一个
复制代码 代码如下:
public static void identityHashCode(){
  //str1 str2为两个不同的String对象
  String str1 = new String("helloWorld");
  String str2 = new String("helloWorld");
  //由于String类重写了hashCode()方法 所以 他们的HashCode是一样的
  System.out.println(str1.hashCode()+" : "+str2.hashCode());
  //由于他们不是同一个对象所以他们的计算出来的HashCode时不同的。
  //实际上该方法使用的时最原始的HashCode计算方法即Object的HashCode计算方法
  System.out.println(System.identityHashCode(str1) + " : "+ System.identityHashCode(str2));
  String str3 = "hello";
  String str4 = "hello";
  //由于他们引用的是常量池中的同一个对象 所以他们的HashCode是一样的
  System.out.println(System.identityHashCode(str3) + " : "+ System.identityHashCode(str4));
  
 }

Runtime类的常用用法
每个 Java 应用程序都有一个 Runtime 类实例,使应用程序能够与其运行的环境相连接。
复制代码 代码如下:
class RunTimeTest
{
 public static void main(String[] args) throws Exception
 {
  getJvmInfo();
  //execTest();
 }
 public static void getJvmInfo(){
  //获取Java运行时相关的运行时对象
  Runtime rt = Runtime.getRuntime();
  System.out.println("处理器数量:" + rt.availableProcessors()+" byte");
  System.out.println("Jvm总内存数 :"+ rt.totalMemory()+" byte");
  System.out.println("Jvm空闲内存数: "+ rt.freeMemory()+" byte");
  System.out.println("Jvm可用最大内存数: "+ rt.maxMemory()+" byte");
 }
 public static void execTest()throws Exception{
  Runtime rt = Runtime.getRuntime();
  //在单独的进程中执行指定的字符串命令。
  rt.exec("mspaint E:\mmm.jpg");
 }
}

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/152580.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号