首先让我们来了解几个基本的概念:
线程(Thread):计算机中最小的执行单元之一,负责执行程序中指定的任务。
多线程(Multithreading):指在同一个程序中同时执行多个线程,避免单一线程运行太慢造成CPU的浪费。
线程返回数据(Thread Return Data):线程计算完成后,将得到的结果返回给主线程,主线程可以做出相应的操作。
为了实现线程返回数据,有两种方法可以用:
方法一:继承Callable接口
Callable接口使用起来基本类似于Runnable接口,只不过Runnable接口的run()方法不能返回结果,而Callable接口的call()方法可以返回一个结果,这个结果可以是任意类型。
使用步骤:
步骤一:编写任务
import java.util.concurrent.Callable;
public class MyCallable implements Callable<String> {
@Override
public String call() throws Exception {
System.out.println(Thread.currentThread().getName() + " start running...");
Thread.sleep(5000);
return "Task successfully completed!";
}
}
步骤二:创建线程池
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
public class CallableTest {
public static void main(String[] args) {
ExecutorService executor = Executors.newSingleThreadExecutor();
步骤三:提交任务
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
public class CallableTest {
public static void main(String[] args) {
ExecutorService executor = Executors.newSingleThreadExecutor();
Future<String> future = executor.submit(new MyCallable());
步骤四:获取线程返回值
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
public class CallableTest {
public static void main(String[] args) {
ExecutorService executor = Executors.newSingleThreadExecutor();
Future<String> future = executor.submit(new MyCallable());
try {
String result = future.get();
System.out.println("Task result: " + result);
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
} finally {
executor.shutdown();
}
}
}
示例一:使用Callable接口获取线程返回结果
import java.util.concurrent.Callable;
import java.util.concurrent.FutureTask;
import java.util.concurrent.ExecutionException;
public class MyCallable implements Callable<String> {
@Override
public String call() throws Exception {
System.out.println(Thread.currentThread().getName() + " start running...");
Thread.sleep(5000);
return "Task successfully completed!";
}
}
public class CallableTest {
public static void main(String[] args) throws InterruptedException, ExecutionException {
FutureTask<String> futureTask = new FutureTask<>(new MyCallable());
new Thread(futureTask).start();
String result = futureTask.get();
System.out.println("Task result: " + result);
}
}
运行结果:
Thread-0 start running...
Task result: Task successfully completed!
方法二:使用join()方法
join()方法的作用是等待线程完成并返回结果,在主线程中调用线程对象的join()方法,主线程会陷入等待,直到子线程执行完成或者超时。
示例二:使用join()方法获取线程返回结果
public class JoinExample {
public static void main(String[] args) throws InterruptedException {
MyThread myThread = new MyThread();
myThread.start();
myThread.join();
System.out.println("Task result: " + myThread.getResult());
}
}
public class MyThread extends Thread {
private String result;
@Override
public void run() {
System.out.println(Thread.currentThread().getName() + " start running...");
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
result = "Task successfully completed!";
}
public String getResult() {
return result;
}
}
运行结果:
Thread-0 start running...
Task result: Task successfully completed!
以上就是Java多线程编程中从线程返回数据的两种方法,希望对你有所帮助。
本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:java多线程编程之从线程返回数据的两种方法 - Python技术站