java 线程返回值

1.传统方式需要新建一个接口类,然后在接口类中将结果在方法中作为参数进行处理

package de.bvb.test3;

public class Test3 {
    public static void main(String[] args) throws Exception {

        Thread t = new Thread(new MyRunnable(6, new Callback<Long>() {

            @Override
            public void handler(Long result) {
                System.out.println(result);
            }
        }));
        t.start();

    }
}

interface Callback<T> {
    void handler(T result);
}

class MyRunnable implements Runnable {
    private long num;
    private Callback<Long> callback;

    public MyRunnable(long num, Callback<Long> callback) {
        super();
        this.num = num;
        this.callback = callback;
    }

    @Override
    public void run() {
        long result = -1l;
        if (num > 0) { // 计算阶乘
            result = 1;
            for (int i = 2; i < num; i++) {
                result *= i;
            }
        }
        if (callback != null) {
            callback.handler(result);
        }
    }
}

2.可以使用java5的新特性,实现Callable这个接口

package de.bvb;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

public class Test2 {
    public static void main(String[] args) throws Exception {
        ExecutorService pool = Executors.newFixedThreadPool(1);
        Future<Long> f1 = pool.submit(new MyCallable(5));
        System.out.println(f1.get().toString());
        pool.shutdown();
    }
}

class MyCallable implements Callable<Long> {
    private long num;

    public MyCallable(long num) {
        super();
        this.num = num;
    }

    @Override
    public Long call() throws Exception {
        long result = -1l;
        if (num > 0) {
            result = 1l;
            for (int i = 2; i < num; i++) {
                result *= i;
            }
        }
        return result;
    }

}

 

posted @ 2016-12-29 14:26  MarcoReus  阅读(239)  评论(0编辑  收藏  举报