Java Questions 1 - 10   «Prev  Next»

Java Thread Creation and State Questions

  1. What happens if you create a thread using the no-arg constructor?

    Answer: The thread will call its own run() method when it istime to start working.

  2. What is the difference between an absolute and relative path?

    Answer:
    An absolute path in Unix beings with a forward slash. The leading slash indicates that this path is starting from the root directory of the system.
    The absolute path of a directory is always the same. A relative path is one that does NOT start with a slash.



  3. One way of terminating a thread in Java is by executing the method Thread.currentThread().interrupt().
    What are other methods of terminating a Java Thread?

    Answer:
    Terminating a thread in Java is a critical operation that must be handled with care to ensure program stability and thread safety. Apart from invoking `Thread.currentThread().interrupt()`, which signals to the thread that it should stop its operation at the next convenient interruption point, there are several other methods for managing thread termination:
    1. Using a Flag: A common and safe strategy to terminate a thread is by employing a boolean flag. The thread checks this flag periodically within its run loop, and gracefully exits if the flag indicates termination. This method ensures that the thread can complete necessary resource cleanup and state saving operations before exiting.
      public class ControlledRunnable implements Runnable {
      private volatile boolean running = true;
      
      public void terminate() {
      running = false;
      }
      
      public void run() {
      while (running) {
      	// Thread operation
      }
      }
      }
      
    2. Using `Thread.join()`: The `join()` method allows one thread to wait for the completion of another. If you want to terminate a thread, you can wait for the thread to complete its execution using the `join()` method. This is a gentle way to ensure that a thread has finished its work before the program continues or exits.
      Thread t = new Thread(new ControlledRunnable());
      t.start();
      // Wait for the thread to finish
      t.join();
      
    3. Using `ExecutorService` Shutdown: When using executor services to manage threads, you can shut down the executor service, which will in turn cause its managed threads to complete execution. Methods like `shutdown()` and `shutdownNow()` provide controlled ways to terminate threads managed by the executor service. `shutdown()` allows previously submitted tasks to execute before terminating, while `shutdownNow()` attempts to stop all actively executing tasks.
      ExecutorService executor = Executors.newFixedThreadPool(1);
      executor.submit(new ControlledRunnable());
      // Initiates an orderly shutdown
      executor.shutdown();
      
    4. Interrupting a Thread: While `Thread.currentThread().interrupt()` sets the interrupt status of the current thread, you can also interrupt other threads to indicate that they should stop their operation. The thread must support interruption by regularly checking its interrupted status and responding appropriately.
      Thread t = new Thread(new ControlledRunnable());
      t.start();
      // Interrupt the thread
      t.interrupt();
      
    5. Deprecated Methods (Not Recommended): Methods such as `Thread.stop()`, `Thread.suspend()`, and `Thread.resume()` are deprecated due to their unsafe nature, as they can leave shared data in inconsistent states and lead to deadlocks. It is strongly advised against using these methods for thread termination.
    Best Practices It is crucial to ensure that threads are terminated safely and gracefully, allowing them to complete critical operations and release resources. Abrupt termination can lead to resource leaks, inconsistent states, and other unpredictable behaviors. The most recommended method for terminating a thread is by using a flag or employing interruption in a way that allows the thread to complete its work and exit cleanly.
    Thread.currentThread().interrupt()


  4. Will Threads start in the order in which they started?

    Answer: No.
    The behavior is not guaranteed. There is nothing in the Java specification that says threads will start running in the order in which they started.

  5. How can you start a thread but tell it not to run, until some other thread has finished?

    Answer:
    Use the join() method

  6. How can you describe a dead thread?

    Answer:
    It is still a Thread Object, just not a thread of execution.

  7. How many times can you call the start method?

    Answer:
    The start method can only be called once.

  8. What happens if you call start() a second time.

    Answer:
    If you call start() a second time, it will cause an exception (an IllegalThreadStateException, which is a kind of RuntimeException)

  9. What state must a thread be in, in order to be selected by the Thread Scheduler?

    Answer:
    Any thread in the runnable state can be chosen by the scheduler to be the one and only running thread.

  10. Which 3 thread-related methods does every class in Java inherit?

    Answer:
    1. public final void wait() throws InterruptedException
    2. public final void notify() throws InterruptedException
    3. public final void notifyAll() throws InterruptedException

SEMrush Software