How to Make the Main Thread Wait for Child Thread Completion in Java
The correct answer is 'C - join'.
The 'join()' method in Java allows the main thread to wait until a child thread completes its execution. Here's why it's the right choice:
- isAlive(): This method checks if a thread is still running but doesn't pause the main thread.
- sleep(): This method simply pauses the current thread for a specified duration, it doesn't depend on another thread's completion.
- join(): This method is designed for thread synchronization. When called on a child thread, the main thread will pause its execution and wait until the child thread finishes. Once the child thread completes, the main thread resumes.
- interrupt(): This method interrupts a thread's execution, it doesn't force the main thread to wait for its completion.
Example:
class MyThread extends Thread {
public void run() {
// Code to be executed by the child thread
}
}
public class MainThread {
public static void main(String[] args) {
MyThread childThread = new MyThread();
childThread.start();
try {
childThread.join(); // Main thread waits for child thread to finish
} catch (InterruptedException e) {
System.out.println("Interrupted: " + e.getMessage());
}
System.out.println("Main thread continues after child thread completes");
}
}
In this example, the 'main' thread will wait at the 'childThread.join()' line until the 'childThread' finishes its execution. Only after that, the main thread will proceed with the remaining code.
原文地址: https://www.cveoy.top/t/topic/ozWe 著作权归作者所有。请勿转载和采集!