Java协程框架Quasar Demo (maven)
主线程随机抽一个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
-
-
运行测试代码
本文来自博客园,作者:HumorChen99,转载请注明原文链接:https://www.cnblogs.com/HumorChen/p/18039665
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 从HTTP原因短语缺失研究HTTP/2和HTTP/3的设计差异
· 三行代码完成国际化适配,妙~啊~