feat: Add comprehensive examples from multithreading and hashing lectures
This commit is contained in:
@@ -0,0 +1,41 @@
|
||||
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();
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user