-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCallableDemo.java
More file actions
47 lines (36 loc) · 1.03 KB
/
CallableDemo.java
File metadata and controls
47 lines (36 loc) · 1.03 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
package ExecutorService;
import java.util.concurrent.*;
public class CallableDemo {
public static void main(String[] args) throws InterruptedException, ExecutionException, TimeoutException {
try(ExecutorService executor= Executors.newCachedThreadPool()){
for (int i = 0; i < 100 ; i++) {
Future<String> res=executor.submit(new Number(i));
String ans=res.get();
if(!ans.isEmpty()){
System.out.println(ans);
}
}
}
}
}
class Number implements Callable<String>{
int n;
Number(int n){
this.n=n;
}
@Override
public String call() throws Exception{
if(isPrime(n)){
return (n+" is Prime by "+Thread.currentThread().getName());
}else{
return("");
}
}
public boolean isPrime(int n){
if (n <= 1) return false;
for (int i = 2; i <= Math.sqrt(n); i++) {
if (n % i == 0) return false;
}
return true;
}
}