7.4.1 如何给 run() 方法传参
下面看一个示例。
- 创建一个类,实现 Runnable 接口,将线程等待 5 秒中后再赋值 ```java package thread;
public class CycleWait implements Runnable { private String value;
@Overridepublic void run() {try {Thread.currentThread().sleep(5000);} catch (InterruptedException e) {e.printStackTrace();}value = "we have data now";}public static void main(String[] args) {CycleWait cw = new CycleWait();Thread t = new Thread(cw);t.start();System.out.println("value: " + cw.value);}
}
<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);
}
}

主线程等待法实现起来比较简单,缺点是需要自己实现循环等待的逻辑,当需要等待的变量比较多时,代码便会显得异常臃肿,并且需要循环多久是不确定的,没法做到精准的控制。
- 使用 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); } }
<br />join 方法能做到比主线程等待法更精准的控制,实现起来更简单,缺点是力度不够细。
- 通过 Callable 接口实现:通过 FutureTask 或者线程池获取<br />在 jdk5 之前,线程是没有返回值的,常常为了有返回值颇费周折,或者想别的不是多线程的办法绕过。现在 Java 有了可返回值的任务,即实现了 Callable 接口的任务。<br />执行 Callable 任务后可以获取到一个 Future 对象,在该对象上调用 get 就可以获取到 Callable 任务返回的 Object。
下面看一下 FutureTask 的源码。<br /><br />FutureTask 的构造函数能够接收 Callable 实现类的实例<br /><br />isDone 用来判断传给它的 Callable 实现类的 call 方法是否已经执行完成<br /><br />没有参数的 get 方法主要是用来阻塞当前调用它的线程,直到 Callable 的实现类的 call 方法执行完毕,能取到返回值<br /><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;
}
}
- 编写一个类,通过 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

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();
}
}
}

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