Ahoj,
zkousel jsem si napsat metodu, ktera by mne spocitala za pomoci rekurze fib. cislo.
Akorat nejak nechapu jak synchronizovat vlakna, ktery maji provadet vypocet.
Byl bych rad za nejaky rady co delam spatne a co vubec neresim atd.
predem dekuji
Prikladam zdrojac:
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package up4jparfibvlakna;
/**
*
* @author johny
*/
public class Pokus {
public static int fib(int n) {
if (n == 0) {
return 0;
}
if (n == 1) {
return 1;
}
return fib(n - 1) + fib(n - 2);
}
public static int parfib(int n, int k) throws InterruptedException {
Thread[] threads = new Thread[k];
for (int i = 0; i < k; i++) {
threads[i] = new Thread(new FibThreed(n));
}
for (Thread t : threads) {
t.start();
}
for (Thread t : threads) {
t.join();
}
return FibThreed.getFibNumber();
}
/**
* @param args the command line arguments
*/
public static void main(String[] args) throws InterruptedException {
System.out.println(parfib(44, 5));
}
public static class FibThreed implements Runnable {
private int n;
private static int fibNumber = 0;
public FibThreed(int n) {
this.n = n;
}
@Override
public void run() {
fibNumber = fib(n);
}
public int getN() {
return n;
}
public static int getFibNumber() {
return fibNumber;
}
}
}