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:

  1. MyThread Class: This class defines a new thread type, inheriting from the Thread class.
  2. run() Method: The run() 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 while MyThread is temporarily inactive.
    • System.out.println('Finished!'): After the pause, this line prints the message 'Finished!' to the console.
  3. InterruptedException Handling:
    • The catch block handles the InterruptedException, which can occur if another thread calls interrupt() 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).

Output:

The code will output:

Finished!

Important Considerations:

  • Interruption: If the main thread or another thread calls myThread.interrupt() while myThread is sleeping, the InterruptedException will 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.
Java Thread Sleep Example: Understanding Output and Interruption

原文地址: https://www.cveoy.top/t/topic/phT5 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录