Java筆記:運行時
阿新 • • 發佈:2018-02-23
free lee file txt 封裝 希望 實例化 end 靜態方法
一、進程
抽象類Process用來封裝進程,即執行的程序。Process主要用作由Runtime的exec方法創建的對象類型或由ProcessBuilder的start方法創建的對象類型的超類。
二、運行時環境
Runtime封裝了運行時環境,不能實例化Runtime對象,而是通過調用靜態方法Runtime.getRuntime方法來獲得當前Runtime對象的引用。一旦獲得當前Runtime對象的引用,就可以調用一些控制Java虛擬機的狀態和行為。
三、內存管理
盡管Java提供了自動的垃圾回收功能,但是有時需要了解對象堆的大小或剩余空間的大小,可以使用totalMemory方法和freeMemory方法。我們直到Java垃圾回收器周期性地運行,回收不再使用的對象。但是,有時會希望在垃圾回收器下次指定運行之前回收廢棄的對象。可以調用gc方法來要求運行垃圾回收器。
class Solution { public static void main(String[] args) { Runtime runtime = Runtime.getRuntime(); Double[] arr = new Double[100000]; for (int i = 0; i < arr.length; i++) arr[i] = 0.0; arr = null; System.out.println(runtime.freeMemory()); runtime.gc(); System.out.println(runtime.freeMemory()); } }View Code
四、執行其他程序
在安全環境中,可以在多任務操作系統下使用Java執行其他重量級的進程。有幾種形式的exec方法運行命名希望運行的程序,並允許提供輸入參數。exec方法返回Process對象,然後可以使用該對象控制Java程序與該新運行的進程的交互方式。因為Java程序可以運行各種平臺和操作系統上,所以exec時環境獨立的。
import java.io.IOException; class Solution { public static void main(String[] args) { Runtime runtime = Runtime.getRuntime(); Process processView Code= null; try { process = runtime.exec("notepad");//運行記事本 process.waitFor();//等待進程關閉 } catch (IOException exc) { System.out.println("Cannot execute notepad"); } catch (InterruptedException exc) { System.out.println("Process interrupted"); } System.out.println(process.exitValue()); } }
五、進程創建類
import java.io.IOException; class Solution { public static void main(String[] args) { try { ProcessBuilder builder = new ProcessBuilder("notepad.exe", "file.txt"); builder.start(); } catch (IOException exc) { System.out.println("Cannot execute notepad"); } } }View Code
六、系統類
通過currentTimeMillis方法可獲取自1970年1月1日午夜到當前時間的毫秒數。
class Solution { public static void main(String[] args) { long begin = System.currentTimeMillis(); try { for (int i = 0; i < 10; i++) { Thread.sleep(1000); long end = System.currentTimeMillis(); System.out.println(end - begin); } } catch (InterruptedException exc) { System.out.println("Thread interrupted"); } } }View Code
復制數組,相較於普通循環更快。
class Solution { static int[] copyArray(int[] arr) { int[] cpy = new int[arr.length]; System.arraycopy(arr, 0, cpy, 0, arr.length); return cpy; } public static void main(String[] args) { int[] arr = {1, 2, 3, 4, 5}; int[] cpy = copyArray(arr); for (int i : cpy) System.out.println(i); } }View Code
環境屬性。
class Solution { public static void main(String[] args) { System.out.println(System.getProperties()); } }View Code
Java筆記:運行時