主线程随机抽一个10以内的整数,然后送入整数管道,死循环,且每次循环后休眠若干ms
创建一个Fiber协程,死循环从整数管道里读取,如果读取到的数字不为空则打印出来
-
maven依赖
<!-- 协程Quasar--> <dependency> <groupId>co.paralleluniverse</groupId> <artifactId>quasar-core</artifactId> <version>0.7.10</version> <classifier>jdk8</classifier> </dependency>
-
测试代码
import co.paralleluniverse.fibers.Fiber; import co.paralleluniverse.fibers.SuspendExecution; import co.paralleluniverse.strands.SuspendableRunnable; import co.paralleluniverse.strands.channels.Channels; import co.paralleluniverse.strands.channels.IntChannel; import java.io.IOException; import java.util.Random; import java.util.concurrent.ExecutionException; public class QuasarTest { static void doAll2(){ final IntChannel increasingToEcho = Channels.newIntChannel(10); new Fiber<Void>(new SuspendableRunnable() { @Override public void run() throws SuspendExecution, InterruptedException { while (true){ Integer integer=increasingToEcho.receive(); if(integer!=null&&integer!=0){ System.out.println(String.format("get %s",integer)); }else{ System.out.println("空的"); } } } }).start(); test(increasingToEcho); while (true){ } } static void test(IntChannel c){ try { Random random=new Random(); while (true){ int t=random.nextInt(10)+1; c.send(t); Thread.sleep(200*t); } } catch (SuspendExecution suspendExecution) { suspendExecution.printStackTrace(); } catch (InterruptedException e) { e.printStackTrace(); } } static public void main(String[] args) throws ExecutionException, InterruptedException, SuspendExecution, IOException { doAll2(); } }
-
找到自己maven包路径
-
点进Fiber类,然后向上级找一只找到那个maven依赖quasar-core-0.7.10-jdk8.jar
-
然后复制路径 copy path得到
C:\Users\lenovo\.m2\repository\co\paralleluniverse\quasar-core\0.7.10\quasar-core-0.7.10-jdk8.jar
-
把路径加入到运行参数
-javaagent:C:\Users\lenovo\.m2\repository\co\paralleluniverse\quasar-core\0.7.10\quasar-core-0.7.10-jdk8.jar
-
运行里有个edit configuration编辑配置,把上面的代码复制放到VM options
-
-
运行测试代码