加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

java – 如何将参数传递给线程并获取返回值?

发布时间:2020-12-15 05:17:40 所属栏目:Java 来源:网络整理
导读:public class CalculationThread implements Runnable { int input; int output; public CalculationThread(int input) { this.input = input; } public void run() { output = input + 1; } public int getResult() { return output; }} 别的地方: Thread
public class CalculationThread implements Runnable {

    int input;
    int output;

    public CalculationThread(int input)
    {
        this.input = input;
    }

    public void run() {
        output = input + 1;
    }

    public int getResult() {
        return output;
    }
}

别的地方:

Thread thread = new Thread(new CalculationThread(1));
thread.start();
int result = thread.getResult();

当然,thread.getResult()不起作用(它试图从Thread类调用此方法).

你得到了我想要的东西.我怎样才能在Java中实现这一目标?

解决方法

这是线程池的工作.您需要创建一个Callable< R>这是Runnable返回一个值并将其发送到线程池.

该操作的结果是Future< R>.这是一个指向此作业的指针,它将包含计算值,如果作业失败则不会.

public static class CalculationJob implements Callable<Integer> {
    int input;

    public CalculationJob(int input) {
        this.input = input;
    }

    @Override
    public Integer call() throws Exception {
        return input + 1;
    }
}

public static void main(String[] args) throws InterruptedException {
    ExecutorService executorService = Executors.newFixedThreadPool(4);

    Future<Integer> result = executorService.submit(new CalculationJob(3));

    try {
        Integer integer = result.get(10,TimeUnit.MILLISECONDS);
        System.out.println("result: " + integer);
    } catch (Exception e) {
        // interrupts if there is any possible error
        result.cancel(true);
    }

    executorService.shutdown();
    executorService.awaitTermination(1,TimeUnit.SECONDS);
}

打印:

result: 4

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读