Interview Q&A · Java · 13 questions in this topic

Creating Threads: Runnable vs Thread — Java Interview Q&A

All Java topics

How to create threads with Runnable and Thread, how the scheduler runs them, and key lifecycle rules. Part of Threads & Concurrency · 294 questions in the Java bank.

Which Java APIs support threads?

Answer

The foundation is the Thread class and the Runnable interface in the java.lang package, plus the wait and notify methods on Object for coordination. The java.util.concurrent package adds the modern toolkit, including ExecutorService, Future, locks, concurrent collections, and atomic variables. Together these cover raw thread control and higher level task execution. Interviews expect you to name both the classic APIs and the concurrent package.

Key points

  1. 1java.lang.Thread and java.lang.Runnable for basic thread creation.
  2. 2Object wait, notify, and notifyAll for low level coordination.
  3. 3java.util.concurrent executors, futures, locks, and concurrent collections for modern code.
  4. 4Callable, Future, and CompletableFuture for tasks that return results.

What is the main thread?

Answer

The main thread is the first thread the JVM starts when an application launches, and it runs the main method. It can create child threads, which in turn can create further threads. It is a non-daemon thread, so the JVM keeps running until it and all other non-daemon threads finish. When only daemon threads remain, the JVM is allowed to exit.

How many ways can threads be created?

Answer

The two classic ways are extending the Thread class and implementing the Runnable interface. Modern Java adds more options, such as implementing Callable and submitting it to an ExecutorService, or passing a lambda to a thread or executor. Frameworks also provide thread factories and virtual threads in Java 21 and later. In practice, implementing Runnable or submitting a task to an executor is preferred over subclassing Thread.

Key points

  1. 1Extend Thread and override run, then call start.
  2. 2Implement Runnable and pass it to a new Thread, then call start.
  3. 3Implement Callable and submit it to an ExecutorService for a result.
  4. 4Pass a lambda or method reference to a Thread or an executor, including virtual threads with Thread.ofVirtual.

Learn this topic

Recommended resourcesAffiliate links · may earn us a commission

Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Cloud hosting for side projectsShip the portfolio project that gets you hired — free credits for new accounts.Claim credits