Java异步编程之Deferred

写了很简单的例子,用来测试 https://github.com/OpenTSDB/async

 

通过例子,可以看出Deferred的使用方式,执行顺序,理解了这个例子,基本上就明白了Deferred的工作机制。

 

Maven依赖:

        
            com.stumbleupon
            async
            1.4.1
        

 

Java代码:

import com.stumbleupon.async.Deferred;

import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

import static java.lang.System.out;

public class TestDeferred {
    public static void main(String[] args) throws InterruptedException {
        out.println(Thread.currentThread().getName());

        Deferred deferred = new Deferred<>().addBoth(str -> {
            out.println(Thread.currentThread().getName() + " 1 " + str.toString());
            return str;
        }).addBothDeferring(str -> {
            out.println(Thread.currentThread().getName() + " 2 " + str);

            Deferred d = new Deferred<>().addBoth(s -> {
                out.println(Thread.currentThread().getName() + " 3 " + s.toString());
                return s.toString();
            });

            Executors.newSingleThreadExecutor().execute(() -> {
                out.println(Thread.currentThread().getName() + " started.");
                d.callback("hello");
            });
            return d;
        }).addBoth(str -> {
            out.println(Thread.currentThread().getName() + " 4 " + str.toString());
            return str;
        }).addErrback(str -> {
            out.println(str.toString());
            return str;
        });

        Executors.newSingleThreadExecutor().execute(() -> {
            out.println(Thread.currentThread().getName() + " started.");
//            deferred.callback("hello");
            deferred.callback(new NullPointerException("error."));
        });

        out.println(Thread.currentThread().getName() + " sleeping...");
        TimeUnit.MINUTES.sleep(1);
    }
}

 

输入:

main
main sleeping...
pool-1-thread-1 started.
pool-1-thread-1 1 java.lang.NullPointerException: error.
pool-1-thread-1 2 java.lang.NullPointerException: error.
pool-2-thread-1 started.
pool-2-thread-1 3 hello
pool-2-thread-1 4 hello

 

你可能感兴趣的:(Thinking,java)