Nearby lessons
70 of 125Java - Thread Methods
📌 What You Will Learn
- What a thread is and how it is different from a process
- Two ways to create a thread: Thread class and Runnable interface
- The thread life cycle (states)
- How threads cooperate: synchronized, wait and notify
- The modern way: Executors, Callable and lambdas
Thread Methods is a core concept of the Java language. This lesson explains Common Thread Methods and Thread Class — Constants and Important Methods with complete, runnable code examples, clear step-by-step explanations, and common mistakes to avoid with exam-style MCQs at the end.
Common Thread Methods
| Method | What it does |
|---|---|
| start() | Starts the thread (calls run() in a new thread). |
| run() | The actual job of the thread — override this. |
| sleep(ms) | Make the current thread wait for given milliseconds. |
| join() | Wait for another thread to finish before continuing. |
| setName() / getName() | Give/read a friendly name to the thread. |
| setPriority() | Hint about importance: MIN_PRIORITY(1) to MAX_PRIORITY(10), default 5. |
| isAlive() | true if the thread is still running. |
Example01
Thread Class — Constants and Important Methods
Priority constants
Priority is only a hint to the scheduler — a higher priority thread usually gets more chances, but it is not guaranteed.
Useful methods of the Thread class
| Method | What it does |
|---|---|
| start() | Begins the thread (calls run() in a new thread) |
| run() | The thread's job — override it |
| sleep(ms) | Pause the current thread for the given milliseconds |
| join() | Wait for another thread to finish |
| getName() / setName() | Read / give a name to the thread |
| getPriority() / setPriority() | Read / set the priority (1 to 10) |
| isAlive() | true if the thread is still running |
| currentThread() | Returns the currently running thread object (static) |
| setDaemon(true) / isDaemon() | Mark / check a background helper thread |
| activeCount() | Number of active threads (static) |
Example02
Thread Class — Constants and Important Methods
Example03
📝 Key Takeaways
- A thread is a small unit of work; a process is a running program.
- Create a thread by extending Thread or (better) implementing Runnable.
- Life cycle: NEW -> RUNNABLE -> BLOCKED/WAITING/TIMED_WAITING -> TERMINATED.
- Shared data races when many threads change it; synchronized gives a lock.
- wait/notify let threads talk; they need the lock.
- Deadlock = threads waiting on each other's locks; avoid by consistent lock order.
- Real projects use Executors + Callable instead of raw threads.
🧠 Test Your Knowledge
1 QuestionsProgress: 0 / 1