Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/multithreading/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 从线程获取结果_Java_Multithreading - Fatal编程技术网

Java 从线程获取结果

Java 从线程获取结果,java,multithreading,Java,Multithreading,我正在学习多线程,并且我很难从实现Runnable的线程中获得结果。我的代码如下所示: public class MyRunnable implements Runnable { String result; public void run (){ //calculcate result } public String getResult(){ return result; } } 以及: getResult()不工作,因为'mine'是线程,但我也不能使

我正在学习多线程,并且我很难从实现Runnable的线程中获得结果。我的代码如下所示:

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

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

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

想知道如何得到结果吗?

试试这个:

publicstaticvoidmain(字符串[]args){
MyThread runnable=新的MyThread();
线程地雷=新线程(可运行);
我的;
我的;
runnable.getResult();
}

一条建议:给
MyThread
一个不同的名称,因为它是
可运行的
,可能会被误认为是
线程

您需要保留对
新的MyThread()
对象的引用,并在以后使用该引用。
  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
    }
  }