2013年11月3日星期日

java thread a small problem

The next, the novice, would like to ask why the following code what the results are not right ?

import java.util.concurrent.*;

public class Fibonacci implements Runnable{
private int n = 0;
private int[] fibo;

public Fibonacci(){}
public Fibonacci(int n){
this.n = n;
fibo = new int[n];
}

public String toString(){
String str = "";
for(int i = 0;i < n; i ++){
str += fibo[i] + " ";
}

return str;
}

public void run(){
fibo[0] = 0;
fibo[1] = 1;
n -= 2;

int i = 2;
while(n-- > 0){
fibo[i] = fibo[i - 1] + fibo [i - 2];
i ++;
}
System.out.println(toString());
Thread.yield();
}

public static void main(String[] arg){
ExecutorService exec = Executors.newCachedThreadPool();
for(int i = 0;i < 5;i ++)
exec.execute(new Fibonacci(20));

exec.shutdown();
}
}



In addition, in ExecutorService see Future return type declaration , will explain how the first ?
Thank you ! !
------ Solution ---------------------------------------- ----
I said you did not result gnaw it, so I tried for a long time . . .
toString you used when n, has the run () which is - to -1 it.
becomes
for (int i = 0; i <-1; i + +) {
str + = fibo [i] + "";
}

------ Solution ------------------------------------ --------

first is a generic function declaration , there is no practical significance.
------ For reference only -------------------------------------- -

ah. . Yes, yes , thank you ! !

没有评论:

发表评论