从Java线程类返回值

时间:2015-01-29 21:51:12

标签: java multithreading

下面是一个使用多线程的简单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

3 个答案:

答案 0 :(得分:3)

将结果变量添加到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;

答案 1 :(得分:1)

在Java 8中,你可以做到

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

不使用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());

答案 2 :(得分:0)

以下是要自定义的简单代码段:

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