7.4.1 如何给 run() 方法传参

  • 构造函数传参
  • 成员变量传参
  • 回调函数传参

    7.4.2 如何处理线程的返回值

  • 主线程等待法
    让主线程循环等待,直到目标子线程返回值为止

下面看一个示例。

  1. 创建一个类,实现 Runnable 接口,将线程等待 5 秒中后再赋值 ```java package thread;

public class CycleWait implements Runnable { private String value;

  1. @Override
  2. public void run() {
  3. try {
  4. Thread.currentThread().sleep(5000);
  5. } catch (InterruptedException e) {
  6. e.printStackTrace();
  7. }
  8. value = "we have data now";
  9. }
  10. public static void main(String[] args) {
  11. CycleWait cw = new CycleWait();
  12. Thread t = new Thread(cw);
  13. t.start();
  14. System.out.println("value: " + cw.value);
  15. }

}

![image.png](https://cdn.nlark.com/yuque/0/2021/png/390086/1617539789430-074b9ea4-bc6b-4db7-8031-c84a8dd049d4.png#align=left&display=inline&height=41&margin=%5Bobject%20Object%5D&name=image.png&originHeight=41&originWidth=104&size=1061&status=done&style=none&width=104)<br />按照原先这种多线程的方式去执行,并不能精准控制子线程返回结果的时候才去执行下一个语句。

2. 使用主线程等待法,获取子线程的返回值
```java
package thread;

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 data now";
    }

    public static void main(String[] args) throws InterruptedException {
        CycleWait cw = new CycleWait();
        Thread t = new Thread(cw);
        t.start();
        while (cw.value == null) {
            Thread.currentThread().sleep(100);
        }
        System.out.println("value: " + cw.value);
    }
}

image.png
主线程等待法实现起来比较简单,缺点是需要自己实现循环等待的逻辑,当需要等待的变量比较多时,代码便会显得异常臃肿,并且需要循环多久是不确定的,没法做到精准的控制。

  • 使用 Thread 类的 join() 阻塞当前线程以等待子线程处理完毕 ```java package thread;

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 data now";
}

public static void main(String[] args) throws InterruptedException {
    CycleWait cw = new CycleWait();
    Thread t = new Thread(cw);
    t.start();

// while (cw.value == null) { // Thread.currentThread().sleep(100); // } t.join(); System.out.println(“value: “ + cw.value); } }

![](https://cdn.nlark.com/yuque/0/2021/png/390086/1617539971897-588b5bdd-7735-443f-be81-b127eae08242.png#align=left&display=inline&height=34&margin=%5Bobject%20Object%5D&originHeight=34&originWidth=192&status=done&style=none&width=192)<br />join 方法能做到比主线程等待法更精准的控制,实现起来更简单,缺点是力度不够细。

- 通过 Callable 接口实现:通过 FutureTask 或者线程池获取<br />在 jdk5 之前,线程是没有返回值的,常常为了有返回值颇费周折,或者想别的不是多线程的办法绕过。现在 Java 有了可返回值的任务,即实现了 Callable 接口的任务。<br />执行 Callable 任务后可以获取到一个 Future 对象,在该对象上调用 get 就可以获取到 Callable 任务返回的 Object。

下面看一下 FutureTask 的源码。<br />![image.png](https://cdn.nlark.com/yuque/0/2021/png/390086/1617541051249-f0b629a6-28cd-461f-b79a-a0b85cfa6e91.png#align=left&display=inline&height=240&margin=%5Bobject%20Object%5D&name=image.png&originHeight=240&originWidth=1216&size=204665&status=done&style=none&width=1216)<br />FutureTask 的构造函数能够接收 Callable 实现类的实例<br />![image.png](https://cdn.nlark.com/yuque/0/2021/png/390086/1617541109406-eafbbae8-09e5-49e5-a3af-2d03fad3d596.png#align=left&display=inline&height=151&margin=%5Bobject%20Object%5D&name=image.png&originHeight=151&originWidth=693&size=97285&status=done&style=none&width=693)<br />isDone 用来判断传给它的 Callable 实现类的 call 方法是否已经执行完成<br />![image.png](https://cdn.nlark.com/yuque/0/2021/png/390086/1617541168201-a280c4da-e95b-4710-b705-36037df2d466.png#align=left&display=inline&height=209&margin=%5Bobject%20Object%5D&name=image.png&originHeight=209&originWidth=1232&size=197713&status=done&style=none&width=1232)<br />没有参数的 get 方法主要是用来阻塞当前调用它的线程,直到 Callable 的实现类的 call 方法执行完毕,能取到返回值<br />![image.png](https://cdn.nlark.com/yuque/0/2021/png/390086/1617541245742-980a4a30-35b6-4566-aeac-be91b6a60557.png#align=left&display=inline&height=394&margin=%5Bobject%20Object%5D&name=image.png&originHeight=394&originWidth=1232&size=384079&status=done&style=none&width=1232)<br />带有参数的 get 方法,即加入了一个超时机制,如果在超时时间内还没有获取到 Callable 实现类的 call 方法的返回值时,就会抛出一个异常<br />下面看一个示例。

1. 编写一个类,实现 Callable 接口
```java
package thread;

import java.util.concurrent.Callable;

public class MyCallable implements Callable<String> {
    @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;
    }
}
  1. 编写一个类,通过 FutureTask 获取 ```java package thread;

import java.util.concurrent.ExecutionException; import java.util.concurrent.FutureTask;

public class FutureTaskDemo { public static void main(String[] args) throws ExecutionException, InterruptedException { FutureTask task = new FutureTask<>(new MyCallable()); new Thread(task).start(); if (!task.isDone()) { System.out.println(“task has not finished, please wait!”); } System.out.println(“task return: “ + task.get()); } }

![image.png](https://cdn.nlark.com/yuque/0/2021/png/390086/1617540935496-9c096f6f-4778-46c5-8488-d49484ddf56a.png#align=left&display=inline&height=115&margin=%5Bobject%20Object%5D&name=image.png&originHeight=115&originWidth=278&size=5094&status=done&style=none&width=278)

3. 编写一个类,创建一个线程池,往线程池提交 MyCallable 任务并执行,执行完后获取返回的值
```java
package thread;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

public class ThreadPoolDemo {
    public static void main(String[] args) {
        ExecutorService newCachedThreadPool = Executors.newCachedThreadPool();
        Future<String> future = newCachedThreadPool.submit(new MyCallable());
        if (!future.isDone()) {
            System.out.println("task has not finished, please wait!");
        }
        try {
            System.out.println(future.get());
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        } finally {
            newCachedThreadPool.shutdown();
        }
    }
}

7.4 如何实现处理线程的返回值 - 图2
使用线程池的优点在于可以提交多个实现 Callable 方法的类来让线程池并发的处理结果,这样可以对这些 Callable 类的执行方式做统一管理。