java如何获取线程的返回值

本文详细介绍了在Java中如何在多线程环境下获取线程返回值的四种方法:1) 主线程等待法,通过循环判断获取;2) 使用Thread的join()方法阻塞等待;3) 通过FutureTask类结合Callable接口精确获取;4) 利用线程池进行任务管理和结果获取。每种方法都有其适用场景和特点。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

java实现多线程有三种方式,分别是继承Thread类和实现Runnable,Callable接口,然而这三种方式的run()方法都是无返回值的,那么该如何实现获取线程的返回值呢?

1)主线程等待法

这是最简单的方法,通过判断返回值不为空从而得到返回值,缺点就是不能精准判断子线程是否执行完成,直接看代码:


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 Test {
    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);
    }
}

2)使用Thread类的join()阻塞当前线程以等待子线程执行完成

public class Test {
    public static void main(String[] args) throws InterruptedException {
        TestThread thread = new TestThread();
        thread.start();

        thread.join();

        System.out.println(thread.value);
    }
}

3)通过FutureTask类实现

这种方式应该是比较推荐的,通过实现Callable接口,使用FutureTask启动子线程,通过FutureTask的get()方法即可精准的获取返回值

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 Test {
    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);
    }
}

4)使用线程池

我们还可以使用线程池,来统一管理线程,日常开发中使用最多的就是使用线程池处理某一部分的逻辑,等待所有的线程执行完成,才继续处理下一步骤

public class TestCallable implements Callable<String> {
    private int index;
    private long sleepTime;

    public TestCallable(){

    }

    public TestCallable(int index, long sleepTime) {
        this.index = index;
        this.sleepTime = sleepTime;
    }

    @Override
    public String call() throws Exception {
        System.out.println("TestCallable start...."+index);
        try {
            if(sleepTime > 0){
                Thread.sleep(sleepTime);
            }
            else {
                Thread.sleep(5000);
            }

        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        System.out.println("TestCallable end...."+index);

        return "TestCallable"+index;
    }
}

public class Test {
    public static void main(String[] args) throws ExecutionException, InterruptedException {

        ExecutorService service = Executors.newFixedThreadPool(4);

        Future<String> future1 = service.submit(new TestCallable(1,5000));
        Future<String> future2 = service.submit(new TestCallable(2,6000));
        Future<String> future3 = service.submit(new TestCallable(3,7000));
        Future<String> future4 = service.submit(new TestCallable(4,8000));
        //用完线程池必须关闭,否则当前线程将不会结束
        service.shutdown();

        Map<String,Future<String>> futureMap = new HashMap<>();
        futureMap.put("future1",future1);
        futureMap.put("future2",future2);
        futureMap.put("future3",future3);
        futureMap.put("future4",future4);

        String[] keys = new String[]{"future1","future2","future3","future4"};

        while (!futureMap.isEmpty()){
            for(String key : keys){
                Future<String> future = futureMap.get(key);

                if(future != null && future.isDone()){
                    System.out.println(future.get());
                    futureMap.remove(key);
                }
            }

            System.out.println(futureMap.size());
        }
    }
}

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); } } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值