Skip to content

Commit 2b4f6fc

Browse files
committed
Added Thread Daemon explicit InterruptedException handler
1 parent 05e614f commit 2b4f6fc

File tree

2 files changed

+26
-1
lines changed

2 files changed

+26
-1
lines changed
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
package com.dev.thread;
2+
3+
public class DaemonThreadExplicitHandler {
4+
5+
public static void main(String [] args) {
6+
Thread thread = new Thread(new SleepingThread());
7+
thread.start();
8+
thread.interrupt();
9+
}
10+
11+
private static class SleepingThread implements Runnable {
12+
@Override
13+
public void run() {
14+
while (true) {
15+
try {
16+
Thread.sleep(1000000);
17+
} catch (InterruptedException e) {
18+
return;
19+
}
20+
}
21+
}
22+
}
23+
}

src/main/java/com/dev/thread/TreadDaemon.java

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,8 @@ public class TreadDaemon {
77
public static void main(String[] args) {
88

99
Thread thread = new Thread(new LongComputationTask(new BigInteger("200000000000000"), new BigInteger("1000000000000")));
10+
// Daemon or user Thread not exit if the program exits
11+
thread.setDaemon(true);
1012
thread.start();
1113
thread.interrupt();
1214
}
@@ -30,7 +32,7 @@ private BigInteger calculatePow(BigInteger base, BigInteger power) {
3032
BigInteger result = BigInteger.ONE;
3133

3234
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
35+
// explicitly handle Thread interruption because this method doesn't handle InterruptedException
3436
if (Thread.currentThread().isInterrupted()){
3537
System.out.println("Prematurely interrupted Computation");
3638
return BigInteger.ZERO;

0 commit comments

Comments
 (0)