註冊 登錄
Android 台灣中文網 返回首頁

jianrupan的個人空間 https://apk.tw/?1180935 [收藏] [複製] [分享] [RSS]

日誌

JAVA 學習:Thread 執行緒 應用學習

熱度 1已有 297 次閱讀2021-12-3 14:58 |個人分類:軟體應用| JAVA, 學習:Thread, 執行緒, 應用學習

學習網站:https://www.youtube.com/watch?v=9liopGtCF6w

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

 

1

路過

雞蛋

鮮花

握手

雷人

剛表態過的朋友 (1 人)

評論 (0 個評論)

facelist

您需要登錄後才可以評論 登錄 | 註冊