| 
x
馬上加入Android 台灣中文網,立即免費下載應用遊戲。您需要 登錄 才可以下載或查看,沒有帳號?註冊  public class Counter {     public static int count = 0; // 一個公開靜態屬性 An public static attribute     public static void main(String[] args) throws Exception {         // 計算程式執行的時間 Trace running time         long startTime = System.currentTimeMillis();         /*             Test an easy method to increase count 2 billions times             測試一個簡單的方法, 把數字累加 20 億次         */         for(int i=0; i<200000000; i++) {             Counter.count++;         }         long endTime = System.currentTimeMillis();         System.out.println("單一程序運算時間: "+(endTime-startTime)+" mSecs");           Counter.count = 0;         startTime = System.currentTimeMillis();         /*             Compute in parallel by Thread             使用執行續, 讓工作同時分散進行             We have to design a class implementing Runnable interface and instantiate it.             必須準備一個實作 Runnable 介面的類別, 並產生物件實體             Create thread by object instance implementing Runnable interface             利用實作 Runnable 介面的物件, 建立執行緒         */         Thread t1 = new Thread(new Worker(100000000));         Thread t2 = new Thread(new Worker(100000000));         t1.start(); // 啟動執行緒工作 Start thread         t2.start();         t1.join();  // 等待執行緒工作完成 Wait thread to finish         t2.join();         endTime = System.currentTimeMillis();         System.out.println("雙執行緒運算時間: "+(endTime-startTime)+" mSecs");     } } public class Worker implements Runnable {     private int times;     int count;     // 物件建構子     public Worker(int times) {         this.times = times;     }     // 實作 Runnable 介面 Implement Runnable interface     public void run() {         count = 0;         for(int i=0; i<this.times; i++) {             count++;         }     } }   驗證結果: 單一程序運算時間: 2393 mSecs 雙執行緒運算時間: 2239 mSecs 
 |