Java中獲取線程返回值的常用方法有以下幾種:
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
public class Main {
public static void main(String[] args) {
ExecutorService executor = Executors.newSingleThreadExecutor();
Future<Integer> future = executor.submit(new MyCallable());
try {
int result = future.get();
System.out.println("線程返回值:" + result);
} catch (Exception e) {
e.printStackTrace();
} finally {
executor.shutdown();
}
}
}
class MyCallable implements Callable<Integer> {
@Override
public Integer call() throws Exception {
// 執行耗時任務,返回結果
return 100;
}
}
public class Main {
public static void main(String[] args) {
MyThread myThread = new MyThread();
myThread.start();
try {
myThread.join(); // 等待線程執行結束
int result = myThread.getResult();
System.out.println("線程返回值:" + result);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
class MyThread extends Thread {
private int result;
@Override
public void run() {
// 執行耗時任務
result = 100;
}
public int getResult() {
return result;
}
}
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
public class Main {
public static void main(String[] args) {
FutureTask<Integer> futureTask = new FutureTask<>(new MyCallable());
Thread thread = new Thread(futureTask);
thread.start();
try {
int result = futureTask.get();
System.out.println("線程返回值:" + result);
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
}
}
}
class MyCallable implements Callable<Integer> {
@Override
public Integer call() throws Exception {
// 執行耗時任務,返回結果
return 100;
}
}
這些方法都可以用來獲取線程的返回值,選擇哪種方法取決于實際需求和場景。