1. 什么是纤程?
纤程:用户态的线程,线程中的线程,切换和调度不需要经过OS
2. 纤程和线程的区别
主要的区别是
3. 纤程的优势
- 占有资源很少,启动一个县城操作系统前前后后要为它分配大概1M的资源, 纤程Fiber是4K
- 切换比较简单
- 启动很多个10W+
目前(2020年3月22日)支持内置纤程的语言:Kotlin Scala Go Python(lib)… Java?(open jdk : loom)
4. 纤程的应用场景
很短的计算任务,不需要和内核打交道,并发量高!
5. 纤程的使用(利用Quaser库)
<!-- https://mvnrepository.com/artifact/co.paralleluniverse/quasar-core --><dependency><groupId>co.paralleluniverse</groupId><artifactId>quasar-core</artifactId><version>0.4.0</version></dependency>
import co.paralleluniverse.fibers.Fiber;import co.paralleluniverse.fibers.SuspendExecution;import co.paralleluniverse.strands.SuspendableRunnable;import java.util.concurrent.ExecutionException;/*** 线程和纤程的对比* 启动10000个纤程和10000个线程,分别进行相同的计算量calculate(), 对比线程和纤程的性能*/public class FiberAndThread {//启动的纤程/线程数量public static final int SIZE = 10000;//计算static void calculate() {int result = 0;for (int m = 0; m < 10000; m++) {for (int i = 0; i < 200; i++) {result += i;}}}//测试纤程public static void testFiber() throws ExecutionException, InterruptedException {//开始计时long start = System.currentTimeMillis();//初始化纤程数组Fiber<Void>[] fibers = new Fiber[SIZE];for (int i = 0; i < fibers.length; i++) {fibers[i] = new Fiber<Void>(new SuspendableRunnable() {public void run() throws SuspendExecution, InterruptedException {calculate();}});}//启动for (int i = 0; i < fibers.length; i++) {fibers[i].start();}//加入当前线程for (int i = 0; i < fibers.length; i++) {fibers[i].join();}//结束计时long end = System.currentTimeMillis();//计算并打印耗时System.out.println("纤程耗时"+(end - start));}//测试线程public static void testThread() throws InterruptedException {//开始计时long start = System.currentTimeMillis();Runnable r = new Runnable() {@Overridepublic void run() {calculate();}};//初始化线程数组Thread[] threads = new Thread[SIZE];//填充for (int i = 0; i < threads.length; i++) {threads[i] = new Thread(r);}//启动for (int i = 0; i < threads.length; i++) {threads[i].start();}//加入当前线程for (int i = 0; i < threads.length; i++) {threads[i].join();}//结束计时long end = System.currentTimeMillis();//计算并打印耗时System.out.println("线程耗时"+(end - start));}public static void main(String[] args) throws InterruptedException, ExecutionException {//测试线程for (int i = 0 ; i < 10; i++){testThread();}//测试纤程for (int i = 0 ; i < 10; i++){testFiber();}}}
测试结果:
线程耗时577 线程耗时606
线程耗时605
线程耗时537
线程耗时497
线程耗时507
线程耗时494
线程耗时513
线程耗时501
线程耗时505
纤程耗时143
纤程耗时8
纤程耗时8
纤程耗时6
纤程耗时5
纤程耗时7
纤程耗时5
纤程耗时8
纤程耗时5
纤程耗时4
