利用callable实现多线程

来源:互联网 发布:淘宝如何搜电棍 编辑:程序博客网 时间:2024/05/21 19:47

         之前我们可以利用Thread(Runnable target)构造函数,传入一个实现了Runnable接口的类的对象来构造线程,可是Runnable中的线程执行体只能是run方法,且没有返回值,也不能抛出异常。那么有没有其他方法可以传入其他的代码块,而不需要限制成run方法呢,这时候我们可以利用Callable接口来实现。

         实现了Callable接口的类中可以定义call方法作为线程的执行体,他可以有返回值,也可以抛出异常。只不过Callable接口和Runnable接口没有任何直接关系,因此我们不能用Callable接口来构造线程。

        java提供了Future接口来获得call方法的返回值,并且提供了Future接口的实现类,FutureTask。FutureTask实现了Runnable接口,因为我们可以利用FutureTask对象来构造线程。

      下面的代码演示了这个过程

       

import java.util.concurrent.Callable;import java.util.concurrent.ExecutionException;import java.util.concurrent.FutureTask;class MyCall implements Callable<Integer>{@Overridepublic Integer call() throws Exception {    for(int i=0;i<100;i++)    {    System.out.println(Thread.currentThread().getName() +"  "+i);    }    return 100;}}public class TestCallable {     public static void main(String[] args) {MyCall call = new MyCall();FutureTask<Integer> f = new FutureTask<Integer>(call);Thread t1 = new Thread(f);for(int i=0;i<100;i++){System.out.println(Thread.currentThread().getName()+"  "+i);if(i==20){t1.start();}}try {System.out.println(f.get());} catch (InterruptedException e) {e.printStackTrace();} catch (ExecutionException e) {e.printStackTrace();}}}

原创粉丝点击