java中带返回值的线程简介及其实例
1、建立一个带返回值的线程;
public interface Callable<V>
返回结果并且可能抛出异常的任务。实现者定义了一个不带任何参数的叫做 call 的方法。
Callable 接口类似于 Runnable,两者都是为那些其实例可能被另一个线程执行的类设计的。但是 Runnable 不会返回结果,并且无法抛出经过检查的异常。

2、从类的声明可以看出Callable是一个接口,它里面有一个方法call();它的作用: 计算结果,如果无法计算结果,则抛出一个异常。建立的线程实现接口,必须要实现call()方法,下面我来简单介绍一下个返回姓名的实例;首先建立一个demo实现Callable接口;

3、public class Demo implements Callable{ private String name; public Demo(){ 构造函数 } public Demo(String name){ this.name=name;
重载构造函数 } public Object call() throws Exception { return name;
返回值 } }

4、建立一个测试类;
public class Test { public static void main(String[] args) throws Exception, Exception { ExecutorService es=Executors.newFixedThreadPool(2);
建立线程池 Future<String >name=es.submit(new Demo("zhangsan"));
线程的匿名内部类 System.out.println(name.get());
get()方法获取String, es.shutdown();
关闭线程 }}

5、在写一个多线程的案例
public class SumCallable implements Callable<Integer> { private int max; public SumCallable() { } public SumCallable(int max) { this.max=max; } public Integer call() { int sum=0; for(int i=1;i<=max;i++) { sum+=i; } return sum; }}

6、public class ThreadDemo7 { public static void main(String[] args) throws Exception{ ExecutorService es=Executors.newFixedThreadPool(2); Future<Integer> f1=es.submit(new SumCallable(100)); Future<Integer> f2=es.submit(new SumCallable(200)); System.out.println(f1.get()); System.out.println(f2.get()); es.shutdown(); }}
