Threads, Runnable vs Callable and the Thread Lifecycle
Java multithreading questions start with how to create a thread, Runnable vs Callable, the thread states, and the difference between start and run. These basics lead into every harder concurrency question.
What you will learn
- Create threads with Thread, Runnable, Callable and executors
- Name the six thread states
- Compare sleep, wait, join and yield
Key concepts
Runnable vs Callable
Runnable.run returns nothing and cannot throw checked exceptions. Callable.call returns a value and can throw; submit it to an ExecutorService to get a Future.
start vs run
start() creates a new thread that then calls run(). Calling run() directly just runs the method on the current thread.
States
NEW, RUNNABLE, BLOCKED (waiting for a monitor lock), WAITING (wait, join, park with no timeout), TIMED_WAITING (sleep, wait with timeout), TERMINATED.
sleep vs wait
sleep pauses the thread and keeps any locks it holds. wait must be called inside synchronized on that object, releases the lock, and waits for notify or notifyAll.
Step by step
Ways to run work
// 1. Runnable with a thread (rare in real code)
Thread t = new Thread(() -> System.out.println("hi from " + Thread.currentThread().getName()));
t.start();
t.join(); // wait for it
// 2. Callable with an executor (normal)
ExecutorService pool = Executors.newFixedThreadPool(4);
Future<Integer> f = pool.submit(() -> expensiveCount());
Integer n = f.get(2, TimeUnit.SECONDS);
pool.shutdown();Examples
Daemon threads
Thread metrics = new Thread(this::flushMetricsForever);
metrics.setDaemon(true); // the JVM can exit without waiting for it
metrics.start();Practise it
Try these without looking back. If you can explain each one out loud, you are ready for this question.
- Print numbers 1 to 10 alternately from two threads (odd and even) using wait and notify.
- Explain what happens if you call start() twice on the same thread.
Interview questions
What interviewers ask next on this topic. Answer out loud first, then open the model answer.
Why use an ExecutorService instead of new Thread?
Creating threads is costly and unbounded creation can exhaust memory. Executors reuse a pool of threads, queue tasks, give you Futures and clean shutdown, and centralise thread configuration.
Why must wait be called in a loop?
Because of spurious wake-ups and because another thread may have changed the condition before this one reacquired the lock. Always re-check the condition: while (!ready) lock.wait();
Summary
Prefer executors with Runnable or Callable over raw threads, know the six states, and remember that sleep keeps locks while wait releases them and must be used in a loop.
Stuck on this one? Talk to Sumit.
Keys: F focus mode · ← → previous / next topic · Esc leave focus