如何实现处理线程的返回值

  • 主线程等待法
  • 使用Thread类的join()方法阻塞当前线程以等待子线程处理完毕
  • 通过Callable接口实现:通过FutureTask或线程池获取

方法一

MyRunnable类

//子线程,默认value为null,等待3s之后改变其值
public class MyRunnable implements Runnable{

    private String value;

    @Override
    public void run() {
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        value = "libai";
    }

    public String getValue() {
        return value;
    }
}

测试

public class Main1 {
    public static void main(String[] args) throws InterruptedException {
        MyRunnable mr = new MyRunnable();
        Thread thread = new Thread(mr);
        thread.start();
        while (mr.getValue() == null){
            Thread.sleep(100);
        }
        System.out.println("value=" + mr.getValue());
    }
}

结果
在这里插入图片描述
方法二

测试

public class Main1 {
    public static void main(String[] args) throws InterruptedException {
        MyRunnable mr = new MyRunnable();
        Thread thread = new Thread(mr);
        thread.start();
        thread.join();
        System.out.println("value=" + mr.getValue());
    }
}

结果
在这里插入图片描述
方法三

MyCallable类

public class MyCallable implements Callable<String> {
    private String value;

    @Override
    public String call() throws Exception {
        Thread.sleep(3000);
        value = "libai";
        return value;
    }
}

测试

public class Main2 {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        MyCallable callable = new MyCallable();
        FutureTask<String> futureTask = new FutureTask<>(callable);
        new Thread(futureTask).start();
        if (!futureTask.isDone()) {
            System.out.println("waiting...");
        }
        System.out.println("value=" + futureTask.get());
    }
}

或者

public class Main3 {
    public static void main(String[] args) {
        ExecutorService executorService = Executors.newCachedThreadPool();
        Future<String> future = executorService.submit(new MyCallable());
        if (!future.isDone()) {
            System.out.println("waiting...");
        }
        try {
            System.out.println("value=" + future.get());
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        } finally {
            executorService.shutdown();
        }
    }
}

结果
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值