-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathThreadTerminationExample.java
More file actions
30 lines (26 loc) · 942 Bytes
/
Copy pathThreadTerminationExample.java
File metadata and controls
30 lines (26 loc) · 942 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
class AlarmClock extends Thread {
private volatile boolean running = true; // Volatile ensures visibility across threads
public void run() {
while (running) {
System.out.println("⏰ Alarm ringing...");
try {
Thread.sleep(1000); // Wait for 1 second
} catch (InterruptedException e) {
System.out.println("Alarm Interrupted");
}
}
System.out.println("⏹️ Alarm Stopped!");
}
public void stopAlarm() {
running = false;
}
}
public class ThreadTerminationExample {
public static void main(String[] args) throws InterruptedException {
AlarmClock alarm = new AlarmClock();
alarm.start(); // Start the alarm
Thread.sleep(5000); // Let the alarm ring for 5 seconds
System.out.println("🔘 User turns off the alarm...");
alarm.stopAlarm(); // Stop the alarm
}
}