如何实现处理线程的返回值?

如何实现处理线程的返回值?
1、主线程等待法 缺点:需要自己实现循环等待的逻辑,当需要等待的变量较多时,代码异常臃肿。
2、使用thread类的join()阻挡当前线程以等待子线程处理完毕。  缺点:控制力度不够精细。
3、通过callable接口实现,通过FutureTask Or 线程池获取。

一、那么,直接上代码吧,我们首先开始第一种方法。先创建一个类CycleWait,如下所示:
public class CycleWait implements Runnable {

  private String value;

  @Override
  public void run() {
    try {
      Thread.currentThread().sleep(5000);
    } catch (InterruptedException e) {
      e.printStackTrace();
    }
    value = "we have date now";
  }

  public static void main(String[] args) throws InterruptedException {
    CycleWait wait = new CycleWait();
    Thread thread = new Thread(wait);
    thread.start();
    //当值为null的时候一直循环,直到有值的时候才会返回。
    //少了这一步,则可能取出为空的值。
    while (wait.value == null) {
      try {
        Thread.currentThread().sleep(100);
      } catch (InterruptedException e) {
        e.printStackTrace();
      }
    }
    System.out.println(wait.value);
  }
}

  在循环到CycleWait执行完成时,会输出结果 we have date now。 

二、去掉循环体,使用join方法。给一返回结果一样。

public class CycleWait implements Runnable {

  private String value;

  @Override
  public void run() {
    try {
      Thread.currentThread().sleep(5000);
    } catch (InterruptedException e) {
      e.printStackTrace();
    }
    value = "we have date now";
  }

  public static void main(String[] args) throws InterruptedException {
    CycleWait wait = new CycleWait();
    Thread thread = new Thread(wait);
    thread.start();
    //当值为null的时候一直循环,直到有值的时候才会返回。
    //少了这一步,则可能取出为空的值。
    thread.join();
    System.out.println(wait.value);
  }
}

  三、使用FutureTask获得结果,进行控制。

public class myCallable implements Callable {
  @Override
  public String call() throws Exception {
    String value = "test";
    System.out.println("ready to work");
    Thread.currentThread().sleep(5000);
    System.out.println("task down");
    return value;
  }
}

  

public class FutureTaskDemo {

  public static void main(String[] args) throws ExecutionException, InterruptedException {
    FutureTask<String> futureTask = new FutureTask<String>(new myCallable());
    new Thread(futureTask).start();
    if (!futureTask.isDone()) {
      System.out.println("task has not ");
    }
    System.out.println("task reture:{}" + futureTask.get());
  }
}

  四、线程池的方式。好处:可以实现提交多个myCallable方法的线程,是线程池并发的去处理结果。

public class ThreadPoolDemo {

  public static void main(String[] args) {
    //创建线程池
    ExecutorService executorService = Executors.newCachedThreadPool();
    //提交myCallable的任务去执行
    Future<String> future = executorService.submit(new myCallable());
    if (!future.isDone()) {
      System.out.println("task has not ");
    }
    try {
      System.out.println("task reture:{}" + future.get());
    } catch (InterruptedException e) {
      e.printStackTrace();
    } catch (ExecutionException e) {
      e.printStackTrace();
    } finally {
      //关闭线程池
      executorService.shutdown();
    }
  }

  

 
posted @ 2019-07-31 17:05  左手背右手背  阅读(2274)  评论(0编辑  收藏  举报