測試串行執行和並行執行:
//必須是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