Skip to content

Commit ef91601

Browse files
committed
Add proper logic to stop long-running threads
1 parent 4da3b30 commit ef91601

File tree

2 files changed

+13
-3
lines changed

2 files changed

+13
-3
lines changed

src/com/codecafe/concurrency/thread/joiningthreads/FactorialTask.java

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,10 @@ public BigInteger factorial(long n) {
2222
BigInteger tempResult = BigInteger.ONE;
2323

2424
for (long i = n; i > 0; i--) {
25+
if (Thread.currentThread().isInterrupted()) {
26+
System.out.println(Thread.currentThread().getName() + " is interrupted hence stopping...");
27+
break;
28+
}
2529
tempResult = tempResult.multiply(new BigInteger(Long.toString(i)));
2630
}
2731

src/com/codecafe/concurrency/thread/joiningthreads/Main.java

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@
55

66
public class Main {
77

8-
public static void main(String[] args) throws InterruptedException {
8+
public static void main(String[] args) {
99
List<Long> numbers = List.of(5L, 5653L, 9090909L, 30467L, 27L, 2276L);
1010

1111
List<FactorialTask> factorialTasks = new ArrayList<>();
@@ -24,7 +24,12 @@ public static void main(String[] args) throws InterruptedException {
2424
}
2525

2626
for (Thread th : factorialThreads) {
27-
th.join(2000);
27+
try {
28+
th.join(50);
29+
} catch (InterruptedException e) {
30+
System.out.println("Could not join thread-" + th.getName());
31+
th.interrupt();
32+
}
2833
}
2934

3035
for (int i = 0; i < numbers.size(); i++) {
@@ -33,7 +38,8 @@ public static void main(String[] args) throws InterruptedException {
3338
if (factorialTask.isFinished()) {
3439
System.out.println("Factorial of " + numbers.get(i) + " is " + factorialTask.getResult());
3540
} else {
36-
System.out.println("The calculation for " + numbers.get(i) + " is still in progress");
41+
System.out.println("The calculation for " + numbers.get(i) + " is still in progress by " + factorialThreads.get(i).getName());
42+
factorialThreads.get(i).interrupt();
3743
}
3844
}
3945
}

0 commit comments

Comments
 (0)