多線程的效率一定快嗎?


測試串行執行和並行執行:

 

//必須是final,否則會報錯
    private static final long count = 100000000;
    
    @Test
    public void testEfficiency() throws Exception {
        
        serial();         //串行
        concurrence();         //並行
    }

    private void concurrence() throws InterruptedException {
        long start = System.currentTimeMillis();
        Thread t = new Thread(new Runnable() {
            
            @Override
            public void run() {
                int a = 0;
                for(long i =0;i<count;i++){
                    a ++;
                    a ++;
                    a ++;
                }
                
            }
        });
        
        t.start();
        
        int b = 0;
        for(long i = 0;i<count;i++){
            b --;
            b --;
            b --;
        }
        t.join();
        
        long end = System.currentTimeMillis();
        System.out.println("並行執行時長:"+(end - start));
        
    }

    private void serial() {
        long start = System.currentTimeMillis();
        int a = 0;
        for(long i=0;i<count;i++){
            a ++;
        }
        int b = 0;
        for(long i=0;i<count;i++){
            b --;
        }
        long end = System.currentTimeMillis();
        System.out.println("串行執行時長:"+(end - start));
    }

 

結果:

循環次數

串行時長

並行時長

100萬

0

16

1000萬

15

16

1億

109

63

並發執行的效率不一定比串行執行高,因為多線程在執行的時候會有個搶占CPU資源,上下文切換的過程。

 

IT技術和行業交流群 417691667

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM