綁定帳號登入

Android 台灣中文網

打印 上一主題 下一主題

[教程] JAVA 學習:Thread 執行緒 應用學習

[複製連結] 查看: 23532|回覆: 0|好評: 0
跳轉到指定樓層
樓主
jianrupan | 收聽TA | 只看該作者 回帖獎勵 |倒序瀏覽 |閱讀模式
發表於 2022-1-14 16:36

馬上加入Android 台灣中文網,立即免費下載應用遊戲。

您需要 登錄 才可以下載或查看,沒有帳號?註冊

x
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

「用Android 就來APK.TW」,快來加入粉絲吧!
Android 台灣中文網(APK.TW)
收藏收藏 分享分享 分享專題
用Android 就來Android 台灣中文網(https://apk.tw)
回覆

使用道具 舉報

您需要登錄後才可以回帖 登錄 | 註冊

本版積分規則