您的位置:首页 > 编程语言 > Java开发

JAVA的协程实现

2016-04-26 10:57 323 查看

1. 前言

         在Java中使用协程,一般会用到kilim( https://github.com/kilim/kilim )这个框架。但是看了看其用法,比较难懂。跟之前python所理解的协程的使用有很大的区别。所以就上github看看有没有别的协程框架可以用。然后发现了这个框架(
https://github.com/offbynull/coroutines),也就是下面实现协程所用的框架。

 

2. 介绍

如何创建协程

1. 实现Coroutine接口,重写run方法,在run方法中可以在任意位置调用coutinuation.suspend()方法暂停语句的执行并保存上下文。

2. 协程的运行通过CoroutineRunner对象来实现的。创建一个CoroutineRunner对象,这个对象需要传入一个刚才实现的Coroutine接口类进行构造。

3. 调用coroutineRunner.execute()方法,将会调用Coroutine的run方法。然后run方法里面的语句一直运行,直到run方法中调用了coroutine.suspend()方法或者已经将run方法的语句执行完,执行暂停于此。若再次执行execute方法,将继续从刚才暂停的地方继续执行。比较有意思的地方是,如果run方法已经执行完,再次执行execute方法也是可以的,此时将重新执行run方法。那怎么知道任务是否已经执行完毕呢?在上述的例子中没有表现出来,其实调用coroutineRunner.execute()之后会有一个返回值,false代表整个任务已经执行完毕了,而不是停留在中间。由此就能判断任务是否执行完毕。

 

只需三步,就能创建一个协程了,十分简单。另外,作者提到,coroutine除了有suspend方法之外,还有getContext和setContext方法,具体用法尚未研究。但是知道有suspend就足够了。

但是很快就能发现问题,如果有多个协程,他们之间应该怎样调度,怎样进行上下文切换呢?可见,这是一个十分简单的框架,只是提供了最最基本的功能,作者也没提及这方面的问题。不过也留给了我们创作的空间。

 

3. 实现

3.1 实现Coroutine接口,自定义Task

final class MyCoroutine1 implements Coroutine {
@Override
public void run(Continuation c) {
System.out.println("[TASK 1] In task 1, doing something...");
System.out.println("[TASK 1] Switch to other task.");
c.suspend();
System.out.println("[TASK 1] In task 1, doing something...");
System.out.println("[TASK 1] Switch to other task.");
c.suspend();
System.out.println("[TASK 1] In task 1, doing something...");
System.out.println("[TASK 1] Finish task 1 !");
}
}

final class MyCoroutine2 implements Coroutine {
@Override
public void run(Continuation c) {
System.out.println("[TASK 2] In task 2, doing something...");
System.out.println("[TASK 2] Switch to other task.");
c.suspend();
System.out.println("[TASK 2] In task 2, doing something...");
System.out.println("[TASK 2] Finish task 2 !");
}

}

final class MyCoroutine3 implements Coroutine {
@Override
public void run(Continuation c) {
System.out.println("[TASK 3] In task 3, doing something...");
System.out.println("[TASK 3] Finish task 3 !");
}
}

 

3.2 设计调度器

我的设计是维护一个就绪队列,每次取队头的CoroutineRunner(Task)调用一次execute,如果Task尚未完成,就把它放回队尾,这样就可以使每一个任务得到轮流的执行。

自定义一个MyCoroutineRunner类,join方法用于将Task放进队列,execute方法用于执行队列中的任务。

 class MyCoroutineRunner {
Queue<CoroutineRunner> coroutineQueue = new LinkedList<CoroutineRunner>();
public void join(Coroutine c) {
// 往就绪队列塞Task
coroutineQueue.add(new CoroutineRunner(c));
}
public void execute() {
while (!coroutineQueue.isEmpty()) {
System.out.printf("[MAIN] Current number of tasks: %d\n", coroutineQueue.size());
CoroutineRunner coroutineRunner = coroutineQueue.remove();
boolean notFinish = coroutineRunner.execute(); // 执行协程
if (notFinish) {
// 若协程没有完成,继续丢到队尾
coroutineQueue.add(coroutineRunner);
}
}
}
}

 

3.3 测试代码

主函数代码如下,创建了3个任务,每个任务都有不同的特点(挂起的次数和时机不一样)。

 package com.dct.jay;

import java.util.LinkedList;
import java.util.Queue;

import com.offbynull.coroutines.user.Continuation;
import com.offbynull.coroutines.user.Coroutine;
import com.offbynull.coroutines.user.CoroutineRunner;

public class TestRunner {
public static void main(String args[]) {
MyCoroutineRunner myCoroutineRunner = new MyCoroutineRunner();
myCoroutineRunner.join(new MyCoroutine1());
myCoroutineRunner.join(new MyCoroutine2());
myCoroutineRunner.join(new MyCoroutine3());
System.out.println("=== Start ===");
myCoroutineRunner.execute();
System.out.println("=== All tasks finished ! ===");
}
}

3.4 构建项目

         使用ant构建项目。

需要注意的是,在编译完成之后,运行之前,需要做一次Instrument(插桩、侵入)。

插桩就是在代码中插入一段我们自定义的代码。记得在戴尔IT课程上做的APM系统也有用到插桩技术,为了监控服务器的性能,需要对服务器的字节码插入代码。在这里,也需要进行插桩。难道导入一个包,创建几个对象就能实现协程?当然没那么容易。通过使用这种“黑魔法”才能让语句的执行流程暂停。

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!-- WARNING: Eclipse auto-generated file.
Any modifications will be overwritten.
To include a user specific buildfile here, simply create one in the same
directory with the processing instruction <?eclipse.ant.import?>
as the first entry and export the buildfile again. --><project basedir="." default="build" name="JavaCoroutine">
<property environment="env"/>
<property name="debuglevel" value="source,lines,vars"/>
<property name="target" value="7"/>
<property name="source" value="7"/>
<path id="JavaCoroutine.classpath">
<pathelement location="./bin"/>
<pathelement location="./jar/user-1.1.1.jar"/>

</path>
<taskdef name="InstrumentTask" classname="com.offbynull.coroutines.antplugin.InstrumentTask">
<classpath>
<pathelement location="./jar/ant-plugin-1.1.1-shaded.jar"/>
</classpath>
</taskdef>
<target name="init">
<mkdir dir="bin"/>
<copy includeemptydirs="false" todir="bin">
<fileset dir="src">
<exclude name="**/*.launch"/>
<exclude name="**/*.java"/>
</fileset>
</copy>
</target>
<target name="-post-compile">
<!-- The classpath attribute is a semicolon delimited list of the classpath required by your code. -->
<InstrumentTask classpath="./bin" sourceDirectory="bin" targetDirectory="bin"/>
</target>
<target name="clean">
<delete dir="bin"/>
</target>
<target depends="clean" name="cleanall"/>
<target depends="build-subprojects,
8e3b
build-project,-post-compile" name="build"/>
<target name="build-subprojects"/>
<target depends="init" name="build-project">
<echo message="${ant.project.name}: ${ant.file}"/>
<javac debug="true" debuglevel="${debuglevel}" destdir="bin" includeantruntime="false" source="${source}" target="${target}">
<src path="src"/>
<compilerarg line="-encoding UTF-8 " />
<classpath refid="JavaCoroutine.classpath"/>
</javac>
</target>
<target name="TestRunner">
<java classname="com.dct.jay.TestRunner" failonerror="true" fork="yes">
<classpath refid="JavaCoroutine.classpath"/>
</java>
</target>
</project>


 

3.5 运行

运行结果如下,发现输出与每个预设的task行为是一致的。

 



4. 总结

虽然能够实现协程上下文自由切换,但是仿佛并没有什么实质上的用途,算是一个半成品。像python这种线程是硬伤的语言才需要用到协程这种折衷的策略。协程对于Java来说毕竟还是有点非主流啊!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  Java 协程