如何从线程中获取数组值

时间:2014-09-30 07:23:48

标签: java multithreading

我有一个用Java编写的线程,将前100个斐波那契数字放在一个数组中。如何从线程中获取数字。是否有中断,处理,异常,实现,扩展?我一直在添加东西,试验和错误并没有让我理解。

import java.util.Scanner;
import java.io.*;
import java.lang.Thread;      //don't know if this is needed

public class FibThread extends Thread{

    public FibThread (){
       super();                   
 }
 public void run(int inputNum){
     System.out.println(inputNum);
     long[] fibArray = new long[inputNum];
     fibArray[0]=0;
     fibArray[1]=1;
     fibArray[2]=1;
        for(int i = 3; i<inputNum; i++){
            fibArray[i]= fibArray[i-1] + fibArray[i-2];
       // }
            //System.out.println( );
       // for(int j = 0; j<= inputNum; j++){
            int output = (int) fibArray[i];
            System.out.println(output);

        }

 } 

 public static void main(String[] args){   
        Scanner keyboard = new Scanner(System.in);

        FibThread threadOne;
        int inputNum, itter, output;
        System.out.println("Please enter the number of Fibonacci numbers to be generated: ");
        itter = keyboard.nextInt();

        //inputNum = itter;


        threadOne = new FibThread();

        threadOne.start();


      //  for(int j = 0; j<= inputNum; j++){
       //   int output = (int) fibArray[j];
        //  System.out.println(output);

 }   


}

1 个答案:

答案 0 :(得分:1)

如果您有一个返回值的“任务”,请将其设为Callable

如果你想让callable在后台线程中运行,那么不是自己处理线程的创建和执行,通常最好通过ExecutorService来抽象它。调用者可以通过传入Callable来与服务进行交互,并在计算完成时返回将使用该值填充的Future

要修改您的示例,请将FibThread重命名为FibCalc

public class FibCalc implements Callable<Integer> {
    // We need some way to pass in the initial input - must be through the
    // constructor and we'll store it here
    private final inputNum;

    public FibCalc(int inputNum) {
        this.inputNum = inputNum;
    }

    public int call() {
        // The same as your run() method from before, except at the end:
        ...
        return output;
    }
}

// And now for your main() method
public static void main(String[] args) throws Exception {
     // As before up to:
     ...
     itter = keyboard.nextInt();

     // Create a very simple executor that just runs everything in a single separate thread
     ExecutorService exec = Executors.newSingleThreadExecutor();

     // Create the calculation to be run (passing the input through the constructor)
     FibCalc calc = new FibCalc(itter);

     // Send this to the executor service, which will start running it in a background thread
     // while giving us back the Future that will hold the result
     Future<Integer> fibResult = exec.submit(fibCalc);

     // Get the result - this will block until it's available
     int result = fibResult.get();

     // Now we can do whatever we want with the result
     System.out.println("We got: " + result);
}

如果你必须自己创建一个Thread对象(由于对作业问题的人为约束,或类似的东西 - 我不明白为什么人们会在现实中切实地做到这一点),那么这个方法必须是不同的。由于界面run()必须返回void,因此您无法返回值。所以我的方法是将结果存储在FibThread类的局部变量中,然后向该类添加一个方法(例如public int getResult()),该方法返回该变量。

(如果你这样做,请记住你必须自己处理并发问题(即让调用者知道结果已经准备好)。一种天真的方法,主方法启动线程然后立即调用getResult(),意味着它几乎肯定会在计算完成之前得到一个“空”结果。这个问题的原始解决方案是在生成的线程上调用join(),等待它在访问结果之前完成。)