-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPrimeNumberUsingThreads.java
More file actions
73 lines (56 loc) · 1.76 KB
/
PrimeNumberUsingThreads.java
File metadata and controls
73 lines (56 loc) · 1.76 KB
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
import java.util.Scanner;
public class PrimeNumberUsingThreads {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter upper limit (n): ");
int n = sc.nextInt();
System.out.print("Enter number of threads: ");
int noOfThreads = sc.nextInt();
Thread[] threads = new Thread[noOfThreads];
int rangeSize = n / noOfThreads;
int remainder = n % noOfThreads;
int start = 1;
for (int i = 0; i < noOfThreads; i++) {
int end = start + rangeSize - 1;
if (i == noOfThreads - 1) {
end = n;
}
Check task = new Check(start, end);
threads[i] = new Thread(task);
threads[i].start();
start = end + 1;
}
for (int i = 0; i < noOfThreads; i++) {
try {
threads[i].join();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
System.out.println("All threads finished.");
}
}
class Check implements Runnable {
private int start, end;
public Check(int start, int end) {
this.start = start;
this.end = end;
}
@Override
public void run() {
for (int i = start; i <= end; i++) {
if (isPrime(i)) {
System.out.println(i + " is prime (checked by " + Thread.currentThread().getName() + ")");
}
}
}
private boolean isPrime(int n) {
if (n <= 1) return false;
if (n == 2) return true;
if (n % 2 == 0) return false;
for (int i = 3; i * i <= n; i += 2) {
if (n % i == 0) return false;
}
return true;
}
}