簡體   English   中英

運行單個 java 線程比主線程快嗎?

[英]Running single java thread is faster than main?

我在 java 中做了一些並發實驗。 我有這個素數計算方法,它只是為了模仿一個半昂貴的操作:

static boolean isprime(int n){
    if (n == 1)
        return false;
    boolean flag = false;
    for (int i = 2; i <= n / 2; ++i) {
        if (n % i == 0) {
            flag = true;
            break;
        }
    }
    return ! flag;
}

然后我有這個主要方法,它簡單地計算從 0 到 N 的所有素數,並將結果存儲在一個布爾數組中:

public class Main {

public static void main(String[] args) {
    final int N = 100_000;
    int T = 1;

    boolean[] bool = new boolean[N];
    ExecutorService es = Executors.newFixedThreadPool(T);

    final int partition = N / T;


    long start = System.nanoTime();

    for (int j = 0; j < N; j++ ){
        boolean res = isprime(j);
        bool[j] = res;
    }            
    System.out.println(System.nanoTime()-start);
}

這給了我這樣的結果: 893888901 n/s 848995600 n/s

我也有這個驅動程序代碼,我使用一個執行器服務,我使用一個線程來做同樣的事情:

public class Main {

public static void main(String[] args) {
    final int N = 100_000;
    int T = 1;

    boolean[] bool = new boolean[N];
    ExecutorService es = Executors.newFixedThreadPool(T);

    final int partition = N / T;

    long start = System.nanoTime();


    for (int i = 0; i < T; i++ ){
        final int current = i;
        es.execute(new Runnable() {
            @Override
            public void run() {
                for (int j = current*partition; j < current*partition+partition; j++ ){
                    boolean res = isprime(j);

                    bool[j] = res;
                }

            }
        });
    }

    es.shutdown();
    try {
        es.awaitTermination(1, TimeUnit.MILLISECONDS);
    } catch (Exception e){
        System.out.println("what?");
    }

    System.out.println(System.nanoTime()-start);
}

這給出的結果如下:9523201 n/s,15485300 n/s。

現在第二個例子,如你所見,比第一個例子快得多。 我真的不明白為什么會這樣? 與主線程相比,執行器服務線程(有1個線程)不應該更慢,因為它基本上是按順序完成工作+“喚醒”線程的開銷?

當我開始添加多個線程時,我期待 executorservice 更快,但這有點違反直覺。

這是代碼底部的超時。 如果您將其設置得更高,您將獲得非常相似的執行時間。

es.awaitTermination(1000, TimeUnit.MILLISECONDS);

您提到的第一個主線程的執行時間遠高於您允許第二個主線程等待線程完成的毫秒數。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM