利用Runnable和Callable實現Fibonacci

1. Runnable java

public class ThreadFibonacci implements Runnable {

	public static void main(String args[]){
		Thread t = new Thread(new ThreadFibonacci(18));
		t.start();
	}
	public ThreadFibonacci(int i){
		this.num = i;
	}
	
	@Override
	public void run() {
        for(int i = 0; i < num; i++){
        	System.out.print(next() + " ");
        }
	}

	private int num = 0;
	private int count = 0;

	public Integer next() {
		return fib(count++);
	}

	private int fib(int n) {
		if (n < 2)
			return 1;
		return fib(n - 2) + fib(n - 1);
	}

}

 

2. Callable ide

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

public class CallableFibonacci implements Callable<Integer> {

	public static void main(String args[]) throws InterruptedException, ExecutionException {
        ExecutorService es = Executors.newCachedThreadPool();
        List<Future<Integer>> results = new ArrayList<Future<Integer>>();
        for(int i = 0; i < 18; i++){
        	results.add(es.submit(new CallableFibonacci(i)));
        }
        
        for(Future<Integer> fi : results){
        	System.out.println(fi.get());
        }
	}

	public CallableFibonacci(int i) {
		this.count = i;
	}

	private int count = 0;

	public Integer next() {
		return fib(count++);
	}

	private int fib(int n) {
		if (n < 2)
			return 1;
		return fib(n - 2) + fib(n - 1);
	}

	@Override
	public Integer call() throws Exception {
		return next();
	}

}
相關文章
相關標籤/搜索