Skip to content

Commit 037b398

Browse files
committed
Refactor code for thread termination
1 parent eb7c40c commit 037b398

File tree

2 files changed

+9
-8
lines changed

2 files changed

+9
-8
lines changed

README.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@ Simple and easy to understand code examples for most of the Concurrent APIs prov
1212
- [Callable](./src/com/codecafe/concurrency/thread/basics/designathread/CallableDemo.java)
1313
- [ExecutorService](notes/executorservice.md) - [[code](./src/com/codecafe/concurrency/executorservice/ExecutorServiceDemo.java)]
1414
- [Thread States](./notes/thread-states.md) - [[code](./src/com/codecafe/concurrency/thread/basics/designathread/ThreadStates.java)]
15-
- [Stop a Thread](./src/com/codecafe/concurrency/thread/basics/StopAThreadInMiddle.java)
15+
- [Thread Termination](./src/com/codecafe/concurrency/thread/basics/Main.java)
1616
- [Thread Signalling](./src/com/codecafe/concurrency/threadsignalling)
1717
- [Daemon Thread](./notes/daemon-thread.md) - [[code](./src/com/codecafe/concurrency/thread/daemonthread)]
1818

src/com/codecafe/concurrency/thread/basics/StopAThreadInMiddle.java renamed to src/com/codecafe/concurrency/thread/basics/Main.java

Lines changed: 8 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,15 @@
11
package com.codecafe.concurrency.thread.basics;
22

3-
class MyThread1 extends Thread {
3+
class LongComputationTask implements Runnable {
44

5+
@Override
56
public void run() {
6-
// Intentional infinite loop
7+
// Intentional infinite loop to simulate a long computation task
78
for (; ; ) {
89
// Returns true if the thread is interrupted
9-
if (interrupted()) {
10+
if (Thread.currentThread().isInterrupted()) {
1011
// You are supposed to roll back or reverse the operation in progress and stop
11-
System.out.println("Thread is interrupted hence stopping...");
12+
System.out.println("\nThread is interrupted hence stopping...");
1213
// Terminates the loop
1314
break;
1415
}
@@ -18,14 +19,14 @@ public void run() {
1819

1920
}
2021

21-
public class StopAThreadInMiddle {
22+
public class Main {
2223

2324
public static void main(String[] args) {
24-
MyThread1 th = new MyThread1();
25+
Thread th = new Thread(new LongComputationTask());
2526
th.start();
2627

2728
try {
28-
Thread.sleep(10);
29+
Thread.sleep(50);
2930
} catch (InterruptedException e) {
3031
e.printStackTrace();
3132
}

0 commit comments

Comments
 (0)