gpt4 book ai didi

java - Java 线程类的返回值

转载 作者:行者123 更新时间:2023-12-01 18:18:38 25 4
gpt4 key购买 nike

下面是一个使用多线程的简单 Java 类,我的问题是,有没有办法存储每个线程的 randomNumber(可能在名为 randomNumberOne 或 randomNumberTwo 的变量中),以便我可以使用它们得到两者的总和并返回它?我知道这个例子听起来很愚蠢,但基本上使用我的真实代码,我从每个线程返回一个值,并希望获得它们的平均值。我还没有找到任何在 java 中返回线程值的解决方案(而且我对多线程完全陌生)。

public class Example {
public static void main(String[] args){
MathThread one = new MathThread();
MathThread two = new MathThread();

one.start();
two.start();
}
}

class MathThread extends Thread{
public MathThread(){
}

public void run(){
Random rand = new Random();

int randomNumber = rand.nextInt((100 - 1) + 1) + 1;
System.out.println(randomNumber);
}

输出

5
33

最佳答案

将结果变量添加到您的 MathThread 类,并在加入线程后获取值:

class MathThread extends Thread
{
private int result;
public int getResult()
{
this.join();
return result;
}

public void run()
{
// ...

result = randomNumber;
}
}

one.start();
two.start();

double average = (one.getResult() + two.getResult()) / 2.0;

关于java - Java 线程类的返回值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28225319/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com