-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathStopThreadExample.java
More file actions
34 lines (29 loc) · 949 Bytes
/
StopThreadExample.java
File metadata and controls
34 lines (29 loc) · 949 Bytes
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
class MyThread extends Thread {
private volatile boolean running = true; // Volatile ensures visibility across threads
public void run() {
while (running) {
System.out.println(getName() + " is running...");
try {
Thread.sleep(1000); // Simulate work
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println(getName() + " has stopped!");
}
public void stopThread() {
running = false; // Set flag to false, thread will exit loop
}
}
public class StopThreadExample {
public static void main(String[] args) {
MyThread t1 = new MyThread();
t1.start();
try {
Thread.sleep(5000); // Let thread run for 5 sec
} catch (InterruptedException e) {
e.printStackTrace();
}
t1.stopThread(); // Stop the thread gracefully
}
}