/* * The MIT License (MIT) * * Copyright (c) 2015 Camil Staps * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package com.camilstaps.fibonacci; /** * Calculate a fibonacci number * @author Camil Staps s4498062 */ public class ParFib implements Runnable { private final int n; private int result = 0; /** * Create a new instance * @param n the index of the fibonacci number to calculate */ public ParFib(int n) { this.n = n; } @Override public void run() { calculate(n); } public int getResult() { return result; } /** * Calculate the nth number of the Fibonacci sequence. * * This implementation uses two threads if n > 2: one to calculate the * (n-1)th fibonacci number, and one to calculate the (n-2)th fibonacci * number. That is a really silly approach, since many threads will be * created and many numbers will be calculated many times. * As an example, to calculate for n=10, we will calculate the 8th number * twice: once for n=10 (10-2=8) and once for n=9 (9-1=8). The 7th number * will be calculated thrice, and this amount increases for lower numbers. * But hey, the assignment asked for a solution with threads. * * @param n */ private void calculate(int n) { if (n < 3) { result = 1; return; } ParFib pf1 = new ParFib(n - 1); ParFib pf2 = new ParFib(n - 2); Thread t1 = new Thread(pf1); Thread t2 = new Thread(pf2); t1.start(); t2.start(); try { t1.join(); t2.join(); } catch (InterruptedException ex) { System.err.println(ex.toString()); } if (pf1.getResult() != 0 && pf2.getResult() != 0) { result = pf1.getResult() + pf2.getResult(); } } }