Skip to content

Commit 05e614f

Browse files
committed
Added Thread Daemon and Thread interruption
1 parent 492be82 commit 05e614f

File tree

1 file changed

+44
-0
lines changed

1 file changed

+44
-0
lines changed
Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
package com.dev.thread;
2+
3+
import java.math.BigInteger;
4+
5+
public class TreadDaemon {
6+
7+
public static void main(String[] args) {
8+
9+
Thread thread = new Thread(new LongComputationTask(new BigInteger("200000000000000"), new BigInteger("1000000000000")));
10+
thread.start();
11+
thread.interrupt();
12+
}
13+
14+
private static class LongComputationTask implements Runnable{
15+
private BigInteger base;
16+
private BigInteger power;
17+
18+
public LongComputationTask(BigInteger base, BigInteger power){
19+
this.base = base;
20+
this.power = power;
21+
}
22+
23+
24+
@Override
25+
public void run() {
26+
System.out.println( base + " ^ "+ power + " = " + calculatePow(base, power));
27+
}
28+
29+
private BigInteger calculatePow(BigInteger base, BigInteger power) {
30+
BigInteger result = BigInteger.ONE;
31+
32+
for (BigInteger i = BigInteger.ZERO; i.compareTo(power) !=0 ; i = i.add(BigInteger.ONE)){
33+
// explicitly handle Thread interruption because this method doesn't handle ThreadInterruptException
34+
if (Thread.currentThread().isInterrupted()){
35+
System.out.println("Prematurely interrupted Computation");
36+
return BigInteger.ZERO;
37+
}
38+
result = result.multiply(base);
39+
}
40+
41+
return result;
42+
}
43+
}
44+
}

0 commit comments

Comments
 (0)