Background:
Java has supported multithreading from the very beginning. Threads allow for the execution of multiple tasks in parallel, effectively utilizing multi-core processors. The JVM provides an abstraction layer over the operating system threads.
The Issue:
Creating, managing, and terminating threads requires a clear understanding of their lifecycle, synchronization, and potential race conditions. Careless use of threads can lead to deadlocks, improper resource access, and complicated error logs.
The Solution:
In Java, threads can be created by extending the Thread class or implementing the Runnable interface, as well as through modern tools like ExecutorService. It's important to correctly terminate threads, manage their lifecycle, and synchronize access to shared data.
Example of creating and terminating a thread:
class MyRunnable implements Runnable { public void run() { System.out.println("Thread is running"); } } public class ThreadExample { public static void main(String[] args) { Thread t = new Thread(new MyRunnable()); t.start(); // starting the thread try { t.join(); // waiting for completion } catch (InterruptedException e) { e.printStackTrace(); } } }
Key features:
start() method, not run() (otherwise there will be no real parallelism)join()IllegalThreadStateExceptionCan a thread be restarted after it has completed?
No. After completion, a thread is considered "dead", and calling start() again will lead to IllegalThreadStateException.
What is the difference between calling t.run() and t.start()?
t.run() simply invokes the run method in the current thread, without creating a new execution thread. Only t.start() creates a separate OS thread.
What happens if a thread terminates with an unhandled exception?
If an unhandled exception is thrown, the thread will terminate abnormally, and its stack trace will be printed to the error stream, while other threads remain unaffected.
run() instead of start()InterruptedException)A programmer starts a thread using the run() method, thinking it runs in parallel with main, but in reality, everything executes sequentially.
Pros:
Cons:
Correct use of start(), proper exception handling, applying join() to wait for thread termination.
Pros:
Cons: