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 a thread to wait until another thread completes its execution. Here's how it works:
- Calling
join(): When a thread callsjoin()on another thread, it essentially pauses its own execution and waits for the target thread to finish. - Waiting for Completion: The calling thread will block until the target thread's
run()method completes. - Resuming Execution: Once the target thread finishes, the calling thread resumes its execution.
Example:
class MyThread extends Thread {
public void run() {
// Code to be executed by the child thread
System.out.println("Child thread is running");
}
}
public class MainThread {
public static void main(String[] args) {
MyThread childThread = new MyThread();
childThread.start();
try {
childThread.join(); // Wait for child thread to complete
} catch (InterruptedException e) {
System.out.println("Main thread interrupted");
}
System.out.println("Main thread continues after child thread completion");
}
}
Why Other Options Are Incorrect:
isAlive(): This method checks if a thread is still running but doesn't make the calling thread wait for it to finish.sleep(): This method causes the calling thread to pause for a specified duration, but it doesn't guarantee that the target thread will have completed by the time the sleep ends.interrupt(): This method is used to interrupt a thread, but it doesn't directly make the calling thread wait for the target thread's completion.
原文地址: https://www.cveoy.top/t/topic/oz07 著作权归作者所有。请勿转载和采集!