Create and start a new thread in java

This is the basic question asked in any entry-level Java interview. Knowledge of threads is very important to be an efficient and good Java programmer. We will see how to create and start a new thread in Java. Creating a thread in Java is easy and it can be achieved by one of the following 2 ways.

  1. By implementing Runnable interface (java.lang.Runnable).
  2. By sub-classing Thread class (java.lang.Thread)

1. By implementing Runnable interface

  • Above class is implementing Runnable interface. Runnable interface has only one method run(). run() contains the task to be performed by a thread.
  • We are creating a thread on line 12. A thread can be created by passing a Runnable object as an argument to Thread constructor.
  • A thread is started by calling start() on thread object.

2. Create a new thread by sub-classing Thread class

  • Above class is sub-classing java.lang.Thread class. Thread class already implements Runnable interface. So, Thread class has an implementation of run().  To specify your threads task, you have to override run().
  • We can create a thread by creating object of a class which extends java.lang.Thread class. (line 12 in above code)
  • Start the thread by calling start() on the thread object. start() calls run() on your thread.

Note 1 : A thread is started by calling start() on thread object. start() calls run() to execute your task. To start a new thread do not call run() directly. If you call run() directly, code in run() will be executed in current thread and not in new thread.

Note: 2: You can create thread anonymously also. See below code snippet.

You can further reduce code. See following snippet.

Above way of creating and starting a thread is preferred when task to be done by the thread is small.

Preferred way to create a thread in Java.

Preferred way to create a thread is to implement Runnable interface.

 

I hope above explanation is easy to follow. Your questions and comments are most welcome.

Leave a Reply

*

Get more stuff like this
in your inbox

Subscribe to our mailing list and get interesting stuff and updates to your email inbox.

Thank you for subscribing.

Something went wrong.