java实现线程返回值
时间: 2023-11-18 16:45:59 浏览: 150
java实现线程返回值的方法有多种。其中一种方法是通过继承Thread类或者实现Runnable接口,在子线程中设置共享变量来获取返回值。这种方法的缺点是不能精确判断子线程是否执行完成。另一种方法是通过实现Callable接口,使用FutureTask启动子线程,然后使用FutureTask的get()方法获取返回值。这种方法可以精确地获取返回值。
以下是两种方法的示例代码:
方法一,通过设置共享变量获取返回值:
```java
public class TestThread extends Thread {
public String value = null;
@Override
public void run() {
System.out.println("TestThread start....");
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("TestThread end");
value = "TestThread";
}
}
public class Main {
public static void main(String[] args) throws InterruptedException {
TestThread thread = new TestThread();
thread.start();
while (thread.value == null) {
Thread.sleep(100);
}
System.out.println(thread.value);
}
}
```
方法二,使用Callable和FutureTask获取返回值:
```java
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
public class TestCallable implements Callable<String> {
@Override
public String call() throws Exception {
System.out.println("TestCallable start....");
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("TestCallable end");
return "TestCallable";
}
}
public class Main {
public static void main(String[] args) throws ExecutionException, InterruptedException {
FutureTask<String> futureTask = new FutureTask<>(new TestCallable());
Thread thread = new Thread(futureTask);
thread.start();
String value = futureTask.get();
System.out.println(value);
}
}
```
阅读全文