多线程Callable使用

多线程Callable使用,第1张

多线程Callable使用

多线程情况下 使用callable的好处是 可以获取到结果

注意使用callable时 要结合 FutureTask使用,因为FutureTask类继承runnbale接口,Thread类实例化时必须要传runnable或其子类。FutureTask实例化时 要传callable类,所以callable和FutureTask要结合使用 

class CallableThread implements Callable{

  @Override
  public Integer call() throws Exception {
    System.out.println(Thread.currentThread().getName()+"  come in callable");
    TimeUnit.SECONDS.sleep(2);
    return 1024;
  }
}

class RunnableThread implements Runnable{
  @Override
  public void run() {
    System.out.println(Thread.currentThread().getName()+"  come in Runnable");
  }
}
public class CallableDemo {
  public static void main(String[] args) throws ExecutionException, InterruptedException {
    CallableThread callableThread = new CallableThread();
    FutureTask callableTask = new FutureTask<>(callableThread);
    new Thread(callableTask,"callableThread").start();
    System.out.println("before get result");
    Integer callableResult = callableTask.get();
    System.out.println("after get result");
    System.out.println("callableThread result:"+callableResult);

    RunnableThread runnableThread = new RunnableThread();
    FutureTask runnableTask =new FutureTask<>(runnableThread,1);
    new Thread(runnableTask,"runnableThread").start();
    Integer runnableResult = runnableTask.get();
    System.out.println("runnableThread result:"+runnableResult);
  }
}

结果

before get result
callableThread  come in callable
after get result
callableThread result:1024
runnableThread  come in Runnable
runnableThread result:1

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5434921.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-11
下一篇 2022-12-11

发表评论

登录后才能评论

评论列表(0条)

保存