31 lines
1.0 KiB
Java
31 lines
1.0 KiB
Java
package lecture.multithreading.basics;
|
|
|
|
public class IsAliveExample {
|
|
public static void main(String[] args) throws InterruptedException {
|
|
Thread worker = new Thread(new Runnable() {
|
|
@Override
|
|
public void run() {
|
|
System.out.println("👷 Worker started...");
|
|
try {
|
|
Thread.sleep(15000); // Runs for 15 seconds
|
|
} catch (InterruptedException e) {
|
|
e.printStackTrace();
|
|
}
|
|
System.out.println("👷 The worker is done!");
|
|
}
|
|
});
|
|
|
|
System.out.println("before start: " + worker.isAlive()); // false
|
|
|
|
worker.start();
|
|
|
|
System.out.println("Immediately after start: " + worker.isAlive()); // true
|
|
|
|
Thread.sleep(1000); // We wait 1 second
|
|
System.out.println("After 1 second: " + worker.isAlive()); // true (still works)
|
|
|
|
worker.join(); // We wait for the worker to finish
|
|
|
|
System.out.println("After completion of work: " + worker.isAlive()); // false
|
|
}
|
|
} |