java如何获取线程的返回值

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

  • 2
    点赞
  • 20
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值