Files
WS-07-Multithreading-Basics…/src/main/java/lecture/multithreading/basics/InterruptExample.java
T

35 lines
1.1 KiB
Java

package lecture.multithreading.basics;
public class InterruptExample {
public static void main(String[] args) throws InterruptedException {
Thread worker = new Thread(new Runnable() {
@Override
public void run() {
System.out.println("👷 Worker started...");
try {
for (int i = 1; i <= 10; i++) {
System.out.println(" worker: stage " + i);
Thread.sleep(1000); // Each step takes 1 second
}
} catch (InterruptedException e) {
System.out.println("🛑 Worker: Hey! Someone cut me off!");
System.out.println("👷 Worker: OK, I'm finishing...");
}
System.out.println("👷 Goodbye worker!");
}
});
worker.start();
Thread.sleep(6500); // Let the worker work for 6.5 seconds
System.out.println("💀 Main thread: That's enough! Cut it!");
worker.interrupt(); // Tells the worker to stop
worker.join();
System.out.println("Everything is finished!");
}
}