Threading in Java

One of the most common interview questions, What is the difference between a process and a thread?

Process VS Thread:

  • The main difference is that threads (of the same process) run in a shared memory space, while processes run in separate memory spaces.

Process:

  • A process has a self-contained execution environment.
  • Each process has its own memory space.

Threads:

  • Are sometimes called lightweight processes.
  • Threads exist within a process, every process has at least one thread.
  • They share the process’s resources.
  • The Java application starts with the main thread.
  • Each thread is associated with an instance of the class Thread.

Runnable & Thread interface?

To start a new Thread in Java, you have to provide the code that will run in the Thread.

  • Runnable Interface:
    • The Runnable interface defines a single method, run meant to contain the code executed in the Thread.
    • The Runnable object is passed to the Thread constructor.
  • Thread Subclass:
    • The Thread class implements Runnable.
    • An application can extend Thread & implement its own run().
  • Both Thread & Runnable invoke Thread.start in order to start a new Thread.
  • Runnable is used in the case extend is needed along with creating a Thread class.
public class X extends Y implements Runnable{
    @Override
    public void run() {
    }
}

Why can’t we call the run() method directly? instead of calling Thread.start() that will call run()?

  • The start method makes sure that the code is executed in a new Thread.
  • The run is an ordinary method that is overridden by you, so if it’s called directly it will start the Thread in the same running thread.
  • The start method contains the code to trigger a new thread.