简体   繁体   English

Java线程类的返回值

[英]Return Value from Java Thread Class

So below is a simple Java class using multithreading, and my question is, is there a way for me to store the randomNumber from each thread (maybe in a variable called randomNumberOne or randomNumberTwo), so that I can use those to possibly get the sum of both and return it? 所以下面是一个使用多线程的简单Java类,我的问题是,有没有办法让我存储每个线程的randomNumber(也许存储在名为randomNumberOne或randomNumberTwo的变量中),以便可以使用它们来获取总和两者并返回吗? I know this example sounds stupid but basically with my real code I am returning a value from each of my threads and want to get the average of them. 我知道这个例子听起来很愚蠢,但是基本上我的真实代码是我从每个线程中返回一个值,并希望得到它们的平均值。 I haven't found any solution for returning values in threads in java (also I am new to multithreading completely). 我还没有找到任何在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);
}

Output 产量

5
33

Add a result variable to your MathThread class and get the value after you join the thread: 将结果变量添加到MathThread类中,并在join线程后获取值:

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;

In Java 8 you can do 在Java 8中,您可以执行

IntStream.of(0, 2).parallel()
         .map(i -> new Random().nextInt(100)+1)
         .forEach(System.out::println);

Without using the Stream API you can do 无需使用Stream API,您可以执行

List<Future> futures = new ArrayList<>();
for (int i = 0; i < 2; i++)
    futures.add(ForkJoinPool.commonPool()
                            .submit(new Callable<Integer>() {
                                public Integer call() {
                                   return new Random().nextInt(100)+1;
                                }));
for(Future<Integer> future : futures)
   System.out.printl(future.get());

Here is the simple snippet to customize: 这是自定义的简单代码段:

// 1. Create and fill callables to execute
List<Callable<Integer>> callables = new LinkedList<>(); 
// callabels.addAll(makeMeCallables());

// 2. Run using Executor of your choice
ExecutorService service = Executors.newCachedThreadPool();
List<Future<Integer>> results = service.invokeAll(callables);

// 3. Get the results 
if (results.get(i).isDone()) {
    Future f = result.get(i);   
    // process f.get()
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM