System類的常用用法
1,主要獲取系統(tǒng)的環(huán)境變量信息
public static void sysProp()throws Exception{
Map<String,String> env = System.getenv();
//獲取系統(tǒng)的所有環(huán)境變量
for(String name : env.keySet()){
System.out.println(name + " : " +env.get(name));
}
//獲取系統(tǒng)的指定環(huán)境變量的值
System.out.println(env.get("JAVA_HOME"));
//獲取系統(tǒng)的所有屬性
Properties prop = System.getProperties();
//將系統(tǒng)的屬性保存到配置文件中去
prop.store(new FileOutputStream("Prop.properties"),"System properties");
//輸出特定的系統(tǒng)屬性
System.out.println(System.getProperty("os.name"));
}
2,與系統(tǒng)時(shí)間有關(guān)的方法操作
public static void sysTime(){
//獲取系統(tǒng)當(dāng)前的時(shí)間毫秒currentTimeMillis()(返回當(dāng)前時(shí)刻距離UTC 1970.1.1 00:00的時(shí)間差)
Long time = System.currentTimeMillis();
System.out.println(time);
Long time1 = System.nanoTime();//主要用于計(jì)算時(shí)間差單位納秒
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,鑒別兩個(gè)對(duì)象在堆內(nèi)存當(dāng)中是否是同一個(gè)
public static void identityHashCode(){
//str1 str2為兩個(gè)不同的String對(duì)象
String str1 = new String("helloWorld");
String str2 = new String("helloWorld");
//由于String類重寫(xiě)了hashCode()方法 所以 他們的HashCode是一樣的
System.out.println(str1.hashCode()+" : "+str2.hashCode());
//由于他們不是同一個(gè)對(duì)象所以他們的計(jì)算出來(lái)的HashCode時(shí)不同的。
//實(shí)際上該方法使用的時(shí)最原始的HashCode計(jì)算方法即Object的HashCode計(jì)算方法
System.out.println(System.identityHashCode(str1) + " : "+ System.identityHashCode(str2));
String str3 = "hello";
String str4 = "hello";
//由于他們引用的是常量池中的同一個(gè)對(duì)象 所以他們的HashCode是一樣的
System.out.println(System.identityHashCode(str3) + " : "+ System.identityHashCode(str4));
/*輸出如下
-1554135584 : -1554135584
28705408 : 6182315
21648882 : 21648882
*/
}
Runtime類的常用用法
每個(gè) Java 應(yīng)用程序都有一個(gè) Runtime 類實(shí)例,使應(yīng)用程序能夠與其運(yùn)行的環(huán)境相連接。
class RunTimeTest
{
public static void main(String[] args) throws Exception
{
getJvmInfo();
//execTest();
}
public static void getJvmInfo(){
//獲取Java運(yùn)行時(shí)相關(guān)的運(yùn)行時(shí)對(duì)象
Runtime rt = Runtime.getRuntime();
System.out.println("處理器數(shù)量:" + rt.availableProcessors()+" byte");
System.out.println("Jvm總內(nèi)存數(shù) :"+ rt.totalMemory()+" byte");
System.out.println("Jvm空閑內(nèi)存數(shù): "+ rt.freeMemory()+" byte");
System.out.println("Jvm可用最大內(nèi)存數(shù): "+ rt.maxMemory()+" byte");
}
public static void execTest()throws Exception{
Runtime rt = Runtime.getRuntime();
//在單獨(dú)的進(jìn)程中執(zhí)行指定的字符串命令。
rt.exec("mspaint E:\\mmm.jpg");
}
}