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

41 lines
1.2 KiB
Java

package lecture.multithreading.basics;
public class IsInterruptedExample {
public static void main(String[] args) throws InterruptedException {
Thread counter = new Thread(new Runnable() {
@Override
public void run() {
int number = 0;
// Continue until interrupted
while (!Thread.currentThread().isInterrupted()) {
number++;
System.out.println("Count: " + number);
try {
Thread.sleep(50); // 50 milliseconds between each number
} catch (InterruptedException e) {
System.out.println("Interrupted while sleeping!");
break;
}
if (number >= 100) {
break; // We reached 100, don't continue
}
}
System.out.println("Thread stopped! Last count: " + number);
}
});
counter.start();
// Let it work for 2 seconds, then stop it
Thread.sleep(2000);
System.out.println("I'm disconnecting...");
counter.interrupt();
counter.join();
}
}