How to Create Thread in Java? — Java Technical Interview Questions & Answers

How to Create Thread in Java?

How to Create Thread in Java?

  • Two common ways. 1) Extend Thread and override run(), then t.start(). 2) Implement Runnable and pass it to new Thread(r).start(). Prefer Runnable — your class can still extend something else.
  • Work goes in run(). start() asks the JVM to schedule a new thread. If you call run() yourself, it runs on the same thread — no parallelism.
  • lambda: new Thread(() -> System.out.println("hi")).start();
  • Let's take this on the board with one tiny Main class — no extra files. How to Create Thread in Java? — start() schedules the thread; main also prints — order may vary. Start from main, go line by line, and stop at each print. That output is the proof for How to Create Thread ?.

Technical Interview Tip: Two ways: extend Thread or implement Runnable. Always start(), never run() for a new thread.

Code Examples for How to Create Thread in Java?

Example

// Thread demo
public class Main {
  public static void main(String[] args) {
    Thread t = new Thread(() -> System.out.println("Hi from thread"));
    t.start();
    System.out.println("Hi from main");
  }
}

How to Create Thread in Java? — start() schedules the thread; main also prints — order may vary.

How to Explain How to Create Thread in Java? to an Interviewer

Two ways to create a thread?

Extend Thread Implement Runnable

start vs run?

start schedules a new thread run is just the work