一进程
抽象类 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 process = 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());
- }
- }
- View Code
五进程创建类
- 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
来源: http://www.bubuko.com/infodetail-2503589.html