Java中的「協程」

引子java

最近在從新梳理知識體系,在比較編程語言的時候,發現如今流行的lua go rust kotlin之類都有 協程的概念,而java在這塊是比較遲鈍的,而像go這類語言內置了協程,能夠很容易寫出高性能的程序。編程


什麼是」協程「緩存

衆所衆知,進程是OS用來分配資源的最小單位,線程是進行任務執行的最小單位,進程與線程都是OS級別的,二者的運行都依賴於cpu的調度與資源分配,進程與線程都屬於內核態。而協程是在種輕量級別的線程,CPU根本不知道有協程的使用調度,它運行在用戶態,不須要與內核打交道,節省了OS級別的上下文切換app


Java中的協程編程語言

其實java相比go rust等有點落後,沒有內置的協程概念,目前只能使用線程池,事件驅動等形式來支持高性能的程序,java目前有一些協程的類庫quasar,提供了纖程的使用,纖程其實就是協程。下面用quasar寫個例子來驗證一下纖程有多厲害吧。例子很簡單,都是啓動100萬個線程或者線程,每一個線程或許纖程處理2kw次運算。ide


普通線程類性能

package com.fqh.review.base.fiber;

/** * @author fqh * @Description: java 線程例子 * @date 2020/7/28下午4:49 */public class JavaThread {

 /**   * 100w個線程,每一個線程處理2千萬次運算   * @param argus   * @throws InterruptedException   */  public static void main(String[] argus) throws InterruptedException {    long begin = System.currentTimeMillis();    int threadLength=1000000;//100w    Thread[] threads=new Thread[threadLength];    for (int i=0;i<threadLength;i++){      threads[i]=new Thread(()->{        calc();      });    }

   for (int i=0;i<threadLength;i++){      threads[i].start();    }    for (int i=0;i<threadLength;i++){      threads[i].join();    }    System.out.println(System.currentTimeMillis()-begin);  }

 //2kw次計算  static void calc(){    int result=0;    for(int i=0;i<10000;i++){      for(int j=0;j<200;j++){        result+=i;      }    }  }

}
  • 纖程測試類測試

引入quasarJar<dependency>  <groupId>co.paralleluniverse</groupId>  <artifactId>quasar-core</artifactId>  <version>0.7.10</version></dependency>


package com.fqh.review.base.fiber;

import co.paralleluniverse.fibers.Fiber;import java.util.concurrent.ExecutionException;

/** * @author fqh * @Description: java 纖程測試用例 * @date 2020/7/28下午4:48 */public class JavaFiber {  /**   * 100w個纖程,每一個纖程處理2千萬次運算   * @param argus   * @throws InterruptedException   */  public static void main(String[] argus) throws ExecutionException, InterruptedException {    long begin = System.currentTimeMillis();    int fiberLength=1000000;//100w    Fiber<Void>[] fibers=new Fiber[fiberLength];    for (int i=0;i<fiberLength;i++){      fibers[i]=new Fiber(()->{        calc();      });    }

   for (int i=0;i<fiberLength;i++){      fibers[i].start();    }    for (int i=0;i<fiberLength;i++){      fibers[i].join();    }    System.out.println(System.currentTimeMillis()-begin);  }

 //2kw次計算  static void calc(){    int result=0;    for(int i=0;i<10000;i++){      for(int j=0;j<200;j++){        result+=i;      }    }  }}


  • 軟件環境:JDK8lua

  • 機器配置:spa

 

處理器名稱:       Intel Core i7  處理器速度:       2.7 GHz  處理器數目:       1  核總數:          4  L2 緩存(每一個核): 256 KB  L3 緩存:        8 MB  內存:          16 GB


測試結果:

圖片圖片


線程大概在50S左右,纖程在4S左右。。

相關文章
相關標籤/搜索