Thread Methods
Thread methods are built-in methods provided by the Thread class to control thread behaviour — like start() to begin a thread, sleep() to pause it temporarily, and join() to wait for another thread to finish.
1. What are Thread Methods?
Thread methods are built-in methods provided by the Thread class to control thread behaviour — like start() to begin a thread, sleep() to pause it temporarily, and join() to wait for another thread to finish.
2. Why is it used?
These methods give you control over how and when threads run, pause, or wait for each other, which is essential for coordinating multiple threads working together correctly.
3. Real-Life Example
Think of a relay race where one runner must wait (join()) for the previous runner to finish before starting their own leg. These thread methods manage this kind of coordination between multiple independent tasks.
4. Syntax
javathread.start(); Thread.sleep(milliseconds); thread.join(); thread.setPriority(value);
5. Example Program
javapublic class ThreadMethodsDemo { public static void main(String[] args) throws InterruptedException { Thread t = new Thread(() -> System.out.println("Task done")); t.start(); t.join(); // main thread waits for t to finish System.out.println("Main thread continues"); } }
Output:
Task done
Main thread continues6. Key Points to Remember
sleep()pauses the current thread for a given time, without releasing any locks it holds.join()makes the calling thread wait until the target thread finishes execution.- Thread priority (
setPriority()) is only a hint to the scheduler — it doesn't guarantee a strict execution order.