Java Thread Sleep Example: Understanding Output and Interruption
This Java code snippet showcases the use of the Thread.sleep() method within a custom MyThread class extending the Thread class. Let's break down the code and its expected output:
class MyThread extends Thread {
public void run() {
try {
Thread.sleep(1000); // Pause execution for 1 second
System.out.println('Finished!'); // Print after the pause
} catch (InterruptedException e) {
System.out.println('I’m interrupted!'); // Handle interruption
System.exit(-1); // Exit the program
}
}
}
Explanation:
MyThreadClass: This class defines a new thread type, inheriting from theThreadclass.run()Method: Therun()method is the core of a thread's execution. Here's what happens inside:Thread.sleep(1000): The thread pauses for 1000 milliseconds (1 second). This allows other threads to run whileMyThreadis temporarily inactive.System.out.println('Finished!'): After the pause, this line prints the message 'Finished!' to the console.
InterruptedExceptionHandling:- The
catchblock handles theInterruptedException, which can occur if another thread callsinterrupt()on this thread while it's sleeping. - If interrupted, the message 'I’m interrupted!' is printed, and the program exits with an error code (-1).
- The
Output:
The code will output:
Finished!
Important Considerations:
- Interruption: If the main thread or another thread calls
myThread.interrupt()whilemyThreadis sleeping, theInterruptedExceptionwill be thrown, and the catch block will execute. This allows for a controlled way to signal a sleeping thread that it should stop what it's doing. - Thread Synchronization: In multithreaded applications, it's often necessary to synchronize threads to avoid race conditions (where multiple threads access shared data concurrently). Consider using techniques like locks and semaphores for thread safety.
原文地址: https://www.cveoy.top/t/topic/phT5 著作权归作者所有。请勿转载和采集!