Java Thread Basics  

by ne on 2021-09-29 under Java

This is a very basic introduction, if you want to explore immutability and thread safety in more details, you can refer to this series of blogs.

Basically, A Thread is kind of a lightweight process which is executed in parallel to the process from which it is invoked.

Let's think of a basic scenario, where in we want to do an operation in parallel , because it is an independent but heavy operation.

And further, a multithreaded program is generally preferred

  1. if tasks can be (or should be) performed in parallel.
  2. You want to improve your processor usage
  3. Create more responsive application


Thread class in java is the magic class, which has a start() method, which executes your run() method code in an actual separate thread.

The following will invoke a separate thread, but the thread's run method is empty (we didn't override it), it will do nothing. A new thread will be created and die after doing nothing.

 

 

if you run, threadObject.run() directly (and not start()) , the method body will be executed perfectly fine, but not in a separate thread.

By implementing Runnable interface and overriding the run() method, you can provide the instructions you want to run in separate thread.

And you can pass this object (which implemented Runnable interface), to the Thread constructor, and call start() method.

So, the run() method will have the operation-code, implemented from Runnable interface. And thread.start() will run these in a separate thread.

 

The above can be achieved using an anonymous class as well:

 

 

Now, the Thread class also implements Runnable interface. And it already has start() and run() method which we need. So, extending Thread will also serve our purpose :

 

 

With Java 8, it is a bit more fancy, concise and less verbose (using lambda expressions) :