【JAVA新生】kilim版的协程

939 查看

试用了一下 http://docs.paralleluniverse.co/quasar/,发现它是基于JDK 1.7的(主要是fork join pool)。于是拿kilim的代码改了一个纯协程的版本出来。kilim的原始版本(https://github.com/kilim/kilim)里所有的Task都与一个Scheduler绑定,而且官方的例子里都是讲怎么使用Mailbox做messaging的。这个路数和stackless python非常像。两个都是以提供scheduler和messaging为主要api,把协程的api隐藏在下面。为了搞一个更简单的,纯协程api来玩,把kilim里无关的代码都给删了。结果在这里:https://github.com/taowen/kilim

和官方的版本的不同在于,Task添加了一个方法resume(相当于greenlet的switch)。第一次执行resume的时候就是开始执行这个task。如果task yield了,就会中途退出。要在断点继续的话,再次调用resume。

package hello_world;

import kilim.Pausable;
import kilim.Task;

public class Main {

    public static void main(String[] args) {
        Task task = new Task() {
            @Override
            public void execute() throws Pausable {
                System.out.println("hello");
                yield();
                System.out.println("world");
            }
        };
        task.resume();
        System.out.println("hey there");
        task.resume();
    }

}

代码输出如下

hello
hey there
world

要想执行的话。要预先进行weave。其实就是一条命令java kilim.tools.Weaver -d classesDir classesDir。但是要把这条命令整合到gradle的build过程中,还是很不容易的

apply plugin: 'java'
apply plugin: 'application'

mainClassName = 'hello_world.Main'

repositories {
    mavenCentral()
    mavenLocal()
}

configurations {
    kilim
}

dependencies {
    compile 'org.slf4j:slf4j-api:1.7.5'
    compile 'org.github.taowen:kilim:1.0'
    kilim 'org.github.taowen:kilim:1.0'
    testCompile "junit:junit:4.11"
}

task weave(type: JavaExec) {
    classpath "$project.buildDir/classes/main"
    classpath configurations.kilim
    main = "kilim.tools.Weaver"
    args "-d", "$project.buildDir/classes/main", "$project.buildDir/classes/main"
}

classes.dependsOn(weave)

关键点在于classes.dependsOn(weave),这样可以让weave在javaCompile之后,classes之前执行。这种修改别的task的dependency的做法比ANT灵活多了。