Problem: Use Multithreading to create two threads ‘Fibonacci’ and ‘prime’. ‘Fibonacci’ thread will display the series for n terms with 6000ms delay. And ‘prime’ thread will display prime numbers in a given range with 3000ms delay.
while solving the above problem I’ve created the threads but when sleep method executes for the first time it takes the same amount it is provided but while in the second execution prime thread is taking double the amount of time it is has been provided (6000ms).
code
public class Multithreading {
public static void main(String[] args) {
new Fibonacci(10).start();
new Prime(2, 10).start();
}
}
class Fibonacci extends Thread {
int n;
Fibonacci(int n) {
this.n = n;
}
@Override
public void run() {
int fib[] = { 0, 1 };
for (int i = 0; i < n; i++) {
System.out.println("Fibonacci " + i + ": " + fib[0] + " tt" + java.time.LocalTime.now());
int temp = fib[0];
fib[0] = fib[1];
fib[1] = temp + fib[1];
try {
sleep(6000);
} catch (InterruptedException e) {
System.out.println("Interrupt exception occured");
}
}
}
}
class Prime extends Thread {
int from, to;
Prime(int from, int to) {
if (from > to) {
this.from = to;
this.to = from;
} else {
this.from = from;
this.to = to;
}
}
@Override
public void run() {
for (int i = from; i <= to; i++) {
if (prime(i)) {
System.out.println("Prime: " + i + " tt" + java.time.LocalTime.now());
}
try {
sleep(3000);
} catch (InterruptedException e) {
System.out.println("Interrupted Exception occured");
}
}
}
boolean prime(int num) {
for (int i = 2; i <= num / 2; i = i + 2) {
if (num % i == 0)
return false;
}
return true;
}
}
generated output
# generated output
Prime: 2 20:16:53.540280723
Fibonacci 0: 0 20:16:53.540096586
Prime: 3 20:16:56.560805123
Fibonacci 1: 1 20:16:59.564627496
Prime: 5 20:17:02.561778775
Fibonacci 2: 1 20:17:05.565076334
Prime: 7 20:17:08.562604229
Fibonacci 3: 2 20:17:11.565416871
Prime: 9 20:17:14.563291347
Fibonacci 4: 3 20:17:17.565768142
Fibonacci 5: 5 20:17:23.566148373
Fibonacci 6: 8 20:17:29.566462386
Fibonacci 7: 13 20:17:35.566916202
Fibonacci 8: 21 20:17:41.567385889
Fibonacci 9: 34 20:17:47.567805495