1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
|
/*
* The MIT License (MIT)
*
* Copyright (c) 2015 Camil Staps <info@camilstaps.nl>
*
* 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();
}
}
}
|