Quiz: Runnable and Thread in Java: How to Create a Thread

Total: 7 questions

1. 

How do you create a thread in Java?

There are two ways. The first is to extend the java.lang.Thread class, override its run() method and call start() on the object. The second is to implement the java.lang.Runnable interface, whose only method is void run(), and pass the task object to a Thread constructor: new Thread(task).start().

Since Java 8 the shortest form is a lambda:

new Thread(() -> System.out.println("Hello from thread " + Thread.currentThread().getName())).start();
// Hello from thread Thread-0

Either way, only start() starts the thread. The same Runnable object can be passed to several threads, and each one runs its run(). Java 21 also added the Thread.ofPlatform() and Thread.ofVirtual() builders, but the task there is still a Runnable.

2. 

Why can you pass a Runnable to Thread as a lambda or a method reference?

Since Java 8, Runnable is annotated with @FunctionalInterface: it has one abstract method, void run(). So instead of a separate class you can pass a lambda with no parameters or a method reference to a method with the shape void name():

Thread t1 = new Thread(() -> System.out.println("Lambda"), "lambda");
Thread t2 = new Thread(LambdaThreadExample::report, "method-ref");

Before Java 8 the same thing was written as an anonymous class, new Thread(new Runnable() { public void run() { ... } }), and that code still works.

The void run() signature has limits: the method returns no result and declares no checked exceptions. That's why Thread.sleep() inside a lambda has to be wrapped in try/catch (InterruptedException e).

3. 

Which is better: extending Thread or implementing Runnable?

Almost always, implementing Runnable:

  • the task class stays free to extend another class, while extends Thread uses up the only superclass;
  • the task is separated from the thread: the same object can be passed to new Thread(task) any number of times or to an ExecutorService pool through execute() and submit();
  • the task can be written as a lambda or a method reference.

Extending Thread makes sense only when you change the behavior of the thread itself. Its one advantage is that thread methods (getName(), isInterrupted()) are available directly, while a Runnable reaches them through Thread.currentThread().

If the task has to return a result or throw a checked exception, you need a Callable<V>. It can't be passed to a Thread constructor: a Callable goes to ExecutorService.submit() or is wrapped in a FutureTask, which implements both Runnable and Future.

4. 

What is the difference between start() and run() in Java?

start() creates a new thread and calls run() in it. run() is an ordinary method: call it directly, and it executes in the current thread, with no new thread created. The compiler won't catch this mistake.

Thread t = new Thread(() -> System.out.println(Thread.currentThread().getName()));
t.run();   // main
t.start(); // Thread-0

start() can be called only once per object: a second call, even after the thread has finished, throws IllegalThreadStateException. run() can be called any number of times. An overloaded method such as run(String) is never called by the thread: after start() only the no-argument run() executes.

5. 

What constructors does the Thread class have, and what name does a thread get?

Four constructors cover most cases:

  • Thread() - runs the overridden run() of a subclass; without a subclass, nothing;
  • Thread(Runnable target) - runs target.run();
  • Thread(Runnable target, String name) - the same plus a thread name; the default choice, because the name shows up in logs and thread dumps;
  • Thread(String name) - for a Thread subclass with a readable name.

If no name is passed, the JVM assigns Thread-N, where N is the sequence number of the unnamed thread, starting at 0. You set the name with setName() (even after start()) and read it with getName(). Names don't have to be unique. Passing target = null doesn't throw: the thread starts and finishes right away.

6. 

What does Thread.currentThread() return, and what is the main thread in Java?

Thread.currentThread() is a static method that returns the Thread object of the thread executing the code right now, not the one in which the task was created. That's how a Runnable task finds out the name of its thread.

The JVM creates the main thread itself when the program starts; its name is main. On Java 21, System.out.println(Thread.currentThread()) in main prints Thread[#1,main,5,main]: id, name, priority and group. Before Java 19 the format was Thread[main,5,main], without the id.

The program doesn't end together with main: the JVM waits for all non-daemon threads, and threads created from main are non-daemon by default. To keep a thread from holding the program open, call setDaemon(true) before start(); after the thread has started, that call throws IllegalThreadStateException.

7. 

What are Thread.ofPlatform(), Thread.ofVirtual() and Thread.startVirtualThread() in Java 21?

Java 21 gave the Thread class a builder, Thread.Builder: Thread.ofPlatform() creates regular (platform) threads, Thread.ofVirtual() creates virtual threads, and Thread.startVirtualThread(task) starts a virtual thread right away. The task is still a Runnable, and the old constructors keep working.

Thread p = Thread.ofPlatform().name("worker-", 1).start(task); // worker-1
Thread v = Thread.ofVirtual().name("virtual-1").start(task);
Thread u = Thread.startVirtualThread(task);                      // name is an empty string

name("worker-", 1) sets a prefix and a starting number, so the next thread from the same builder is called worker-2. A virtual thread without a name gets an empty string, not Thread-N. unstarted(task) creates a thread without starting it; you start it later with a regular start(). isVirtual() tells you whether a thread is virtual.

Page 1 of 1