-
Notifications
You must be signed in to change notification settings - Fork 24
Expand file tree
/
Copy pathProperlyHandlingInterruptedException.java
More file actions
47 lines (43 loc) · 1.54 KB
/
Copy pathProperlyHandlingInterruptedException.java
File metadata and controls
47 lines (43 loc) · 1.54 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
package org.alxkm.antipatterns.ignoringinterruptedexception;
/**
*
* To resolve this issue, the thread should properly handle InterruptedException by either propagating the exception or breaking out of the loop.
*
* In this revised example, the run method handles the
* InterruptedException by restoring the interrupt status with Thread.currentThread().interrupt() and breaking out of the loop.
* This ensures that the thread stops running as intended.
*
*/
public class ProperlyHandlingInterruptedException implements Runnable {
/**
* The run method performs a long-running task.
* It handles InterruptedException properly by restoring the interrupt status.
*/
@Override
public void run() {
while (true) {
try {
// Simulating long-running task
Thread.sleep(1000);
System.out.println("Working...");
} catch (InterruptedException e) {
// Restore the interrupted status
Thread.currentThread().interrupt();
System.out.println("Thread was interrupted, stopping.");
break;
}
}
}
public static void main(String[] args) {
Thread thread = new Thread(new ProperlyHandlingInterruptedException());
thread.start();
// Interrupt the thread after 3 seconds
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
return;
}
thread.interrupt();
}
}