【问题标题】:Getting results from thread从线程中获取结果
【发布时间】:2017-05-13 13:52:57
【问题描述】:

我正在学习多线程,但我无法从实现 Runnable 的线程中获取结果。我的代码如下所示:

 public class MyRunnable implements Runnable {
  String result;
  public void run (){
    //calculcate result
  }
  public String getResult(){
    return result;
  }
}

和:

  public class Main {
    public static void main(String args[]){
       Thread mine = new Thread (new MyRunnable());
       mine.start();
       mine.join();
       mine.getResult(); //This does not work
    }
  }

mine.getResult() 不起作用,因为 'mine' 是 Thread,但我也不能使 'mine' MyRunnable。我认为扩展 Thread 而不是实现 Runnable 可以解决这个问题,但是我的老师说我们不应该这样做。

我需要 main 中的结果,因为我需要将它与 MyRunnable2 中的 result2 一起写入文件(与 MyRunnable 完全不同的任务)

任何想法如何得到结果?

【问题讨论】:

  • 您需要保留对new MyThread() 对象的引用,并在以后使用该引用。

标签: java multithreading


【解决方案1】:

试试这个:

public static void main(String[] args) {
    MyThread runnable = new MyThread();
    Thread mine = new Thread(runnable);
    mine.start();
    mine.join();
    runnable.getResult();
}

一条建议:给MyThread 起一个不同的名字,因为它是Runnable,它可能会被误认为是Thread

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-11-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多