java多线程2(Callable)

一、使用Callable+Future获取结果:

//实现有返回值的多线程

public class CallableTest {


/**
* @param args
* @throws ExecutionException 
* @throws InterruptedException 
*/
public static void main(String[] args) throws InterruptedException, ExecutionException {
System.out.println("程序开始执行");
    Date ds = new Date();
    //创建一个线程池,即指定同时启动多少个线程
    ExecutorService pool=Executors.newFixedThreadPool(3);
    //创建有多个返回值的任务
    List<Future> ls=new ArrayList<Future>();
    for(int i=0;i<=20;i++){
    Callable  c=new MyCallable(i+" ");  //创建一个称为c的任务
    //执行任务并获取Future对象,Future类提供了提供了检查计算是否完成的方法,等待计算完成并获取结算的结果
    //pool.submit(c)提供一个有返回值的任务用于执行
    Future f =pool.submit(c);
    ls.add(f);
    }
    //关闭线程池
       pool.shutdown();
       //获取所有并发任务的运行结果,用Future对象获取计算计算
       for(Future f :ls){
      //从Future 对象上获取任务的返回值,并输出到控制台
      System.out.println("程序返回结果:"+f.get().toString());
       }
       Date ds2 =new Date();
       System.out.println("----程序结束运行----,程序运行时间【"+ (ds2.getTime() - ds.getTime()) + "毫秒】");  


}


}


class MyCallable implements Callable<Object>{
private String taskNum;

MyCallable(String taskNum ){
this.taskNum=taskNum;
}
@Override
public Object call() throws Exception {
System.out.println(taskNum+"任务启动");
Date ds=new Date();
Thread.sleep(1000);
Date ds1= new Date();
long time=ds1.getTime()-ds.getTime();
System.out.println(taskNum+"任务结束");
return taskNum+"任务返回结果,当前任务时间"+time;
}
}

详见:http://www.cnblogs.com/dolphin0520/p/3949310.html

在中,可以通过实现Callable接口来创建一个带返回值的线程任务。与Runnable接口不同,Callable接口的call()方法可以返回一个结果,而且可以抛出异常。 下面是一个简单的例子: ```java import java.util.concurrent.Callable; public class MyCallable implements Callable<String> { public String call() throws Exception { // 在这里编写你的多线程代码 return "Hello World"; } } ``` 在上面的代码中,我们实现了Callable接口,并且重写了call()方法。在这个方法中,我们可以编写我们的多线程代码,并且使用return语句返回一个结果。 然后,我们可以在主线程中使用Callable创建一个Future对象,以便在后面获取线程的结果。下面是一个使用Future的例子: ```java import java.util.concurrent.*; public class Main { public static void main(String[] args) throws Exception { // 创建一个ExecutorService,用于执行Callable任务 ExecutorService executor = Executors.newSingleThreadExecutor(); // 创建一个Callable任务 Callable<String> callable = new MyCallable(); // 提交任务并返回一个Future对象 Future<String> future = executor.submit(callable); // 等待任务执行完成并获取结果 String result = future.get(); // 输出结果 System.out.println(result); // 关闭ExecutorService executor.shutdown(); } } ``` 在上面的代码中,我们首先创建了一个ExecutorService,它用于执行Callable任务。然后,我们创建了一个Callable任务,并将其提交给ExecutorService。这个方法返回一个Future对象,我们可以使用它来等待任务执行完成并获取结果。最后,我们输出结果,并关闭ExecutorService。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值