当前位置: 移动技术网 > IT编程>开发语言>Java > java多线程返回值使用示例(callable与futuretask)

java多线程返回值使用示例(callable与futuretask)

2019年07月22日  | 移动技术网IT编程  | 我要评论

callable接口类似于runnable,从名字就可以看出来了,但是runnable不会返回结果,并且无法抛出返回结果的异常,而callable功能更强大一些,被线程执行后,可以返回值,这个返回值可以被future拿到,也就是说,future可以拿到异步执行任务的返回值,下面来看一个简单的例子

复制代码 代码如下:

package com.future.test;

import java.io.filenotfoundexception;
import java.io.ioexception;
import java.util.concurrent.callable;
import java.util.concurrent.executionexception;
import java.util.concurrent.executorservice;
import java.util.concurrent.executors;
import java.util.concurrent.futuretask;
import java.util.concurrent.timeunit;
import java.util.concurrent.timeoutexception;

public class mytest {

 // 接收在run方法中捕获的异常,然后自定义方法抛出异常
    //private static throwable exception;
 /**
  * @param args
  */
 public static void main(string[] args) {
  // todo auto-generated method stub
  string result = "";
  executorservice executor = executors.newsinglethreadexecutor(); 
  futuretask<string> future = 
         new futuretask<string>(new callable<string>() {//使用callable接口作为构造参数 
           public string call() { 
             //真正的任务在这里执行,这里的返回值类型为string,可以为任意类型
            try {
      thread.sleep(10000);
     } catch (interruptedexception e) {
      // todo auto-generated catch block
      //exception = e;
      //e.printstacktrace();
     }
           return "11111";
         }}); 
  executor.execute(future); 
  //在这里可以做别的任何事情 
  try { 
      result = future.get(5000, timeunit.milliseconds); //取得结果,同时设置超时执行时间为5秒。同样可以用future.get(),不设置执行超时时间取得结果 
  } catch (interruptedexception e) {
   //system.out.println("任务已经取消");
   future.cancel(true); 
  } catch (executionexception e) { 
   future.cancel(true); 
  } catch (timeoutexception e) { 
   future.cancel(true); 
  } finally { 
      executor.shutdown(); 
  } 
  system.out.println("result:"+result);
 }

 /* public void throwexception() throws filenotfoundexception, ioexception {
         if (exception instanceof filenotfoundexception)
             throw (filenotfoundexception) exception;
         if (exception instanceof ioexception)
             throw (ioexception) exception;
     }*/


}

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网