Java Thread Example

Filed Under: Java

Welcome to the Java Thread Example. Process and Thread are two basic units of execution. Concurrency programming is more concerned with java threads.


A process is a self contained execution environment and it can be seen as a program or application. However a program itself contains multiple processes inside it. Java runtime environment runs as a single process which contains different classes and programs as processes.


Thread can be called lightweight process. Thread requires less resources to create and exists in the process, thread shares the process resources.

Java Thread Example

java thread example
Every java application has at least one thread – main thread. Although there are so many other java threads running in background like memory management, system management, signal processing etc. But from application point of view – main is the first java thread and we can create multiple threads from it.

Multithreading refers to two or more threads executing concurrently in a single program. A computer single core processor can execute only one thread at a time and time slicing is the OS feature to share processor time between different processes and threads.

Java Thread Benefits

  1. Java Threads are lightweight compared to processes, it takes less time and resource to create a thread.
  2. Threads share their parent process data and code
  3. Context switching between threads is usually less expensive than between processes.
  4. Thread intercommunication is relatively easy than process communication.

Java provides two ways to create a thread programmatically.

  1. Implementing the java.lang.Runnable interface.
  2. Extending the java.lang.Thread class.

Java Thread Example – implementing Runnable interface

To make a class runnable, we can implement java.lang.Runnable interface and provide implementation in public void run() method. To use this class as Thread, we need to create a Thread object by passing object of this runnable class and then call start() method to execute the run() method in a separate thread.

Here is a java thread example by implementing Runnable interface.

package com.journaldev.threads;

public class HeavyWorkRunnable implements Runnable {

    public void run() {
        System.out.println("Doing heavy processing - START "+Thread.currentThread().getName());
        try {
            //Get database connection, delete unused data from DB
        } catch (InterruptedException e) {
        System.out.println("Doing heavy processing - END "+Thread.currentThread().getName());

    private void doDBProcessing() throws InterruptedException {


Java Thread Example – extending Thread class

We can extend java.lang.Thread class to create our own java thread class and override run() method. Then we can create it’s object and call start() method to execute our custom java thread class run method.

Here is a simple java thread example showing how to extend Thread class.

package com.journaldev.threads;

public class MyThread extends Thread {

    public MyThread(String name) {

    public void run() {
        System.out.println("MyThread - START "+Thread.currentThread().getName());
        try {
            //Get database connection, delete unused data from DB
        } catch (InterruptedException e) {
        System.out.println("MyThread - END "+Thread.currentThread().getName());

    private void doDBProcessing() throws InterruptedException {

Here is a test program showing how to create a java thread and execute it.

package com.journaldev.threads;

public class ThreadRunExample {

    public static void main(String[] args){
        Thread t1 = new Thread(new HeavyWorkRunnable(), "t1");
        Thread t2 = new Thread(new HeavyWorkRunnable(), "t2");
        System.out.println("Starting Runnable threads");
        System.out.println("Runnable Threads has been started");
        Thread t3 = new MyThread("t3");
        Thread t4 = new MyThread("t4");
        System.out.println("Starting MyThreads");
        System.out.println("MyThreads has been started");

Output of the above java thread example program is:

Starting Runnable threads
Runnable Threads has been started
Doing heavy processing - START t1
Doing heavy processing - START t2
Starting MyThreads
MyThread - START Thread-0
MyThreads has been started
MyThread - START Thread-1
Doing heavy processing - END t2
MyThread - END Thread-1
MyThread - END Thread-0
Doing heavy processing - END t1

Once we start any thread, it’s execution depends on the OS implementation of time slicing and we can’t control their execution. However we can set threads priority but even then it doesn’t guarantee that higher priority thread will be executed first.

Run the above program multiple times and you will see that there is no pattern of threads start and end.

Runnable vs Thread

If your class provides more functionality rather than just running as Thread, you should implement Runnable interface to provide a way to run it as Thread. If your class only goal is to run as Thread, you can extend Thread class.

Implementing Runnable is preferred because java supports implementing multiple interfaces. If you extend Thread class, you can’t extend any other classes.

Tip: As you have noticed that thread doesn’t return any value but what if we want our thread to do some processing and then return the result to our client program, check our Java Callable Future.

Update: From Java 8 onwards, Runnable is a functional interface and we can use lambda expressions to provide it’s implementation rather than using anonymous class. For more details, check out Java 8 Functional Interfaces.


  1. Bao T Huynh says:

    thank you for everything

  2. sam, says:

    Threads question:-

    Shipping Purchase Order

    The Shipping Company wants to analyze the number of purchase orders raised in a month over an year. Since the company has large amount of this historical data of the purchases, to make the processing faster the tech-team decides to implement the report generation using multi-threading.

    Given the order id and the date of purchases, Print all the months that has a minimum of 1 purchase within the month using threads.

    Create a class named TotalOrderThread that implements the Runnable interface with the following private member variables
    • List input
    • Map orderMap
    Include appropriate getters and setters.
    Include a parameterized constructor with following order (input, orderMap).

    And also include the following override methods in the class,

    No Method Name Method Description
    1 public void run() Override the run method, here you iterate the csv list(order), compute the number of order
    placed for a certain month and store the value in a hashmap with month number as key and
    value as number of purchase order

    Create the class named as Main, Get the inputs in the Main method, get n, the number of orders, the payment details and the number of threads to be executed. Split the list into sub lists depending on the number of threads. In the main method once the threads execution are complete, Print the report.

    [Note: Strictly adhere to the object oriented specifications given as a part of the problem statement. Use the same class names, attribute names and method names.]

    Input Format:

    The first line of input contains an integer n, the number of orders.
    The next n lines contains comma-separated strings that corresponds to the order details.
    The next line contains an integer t, the number of threads to be executed.

    Output Format :
    Refer sample input and output for formatting specifications.

    [All text in bold corresponds to input and rest corresponds to output.]

    Sample Input and Output :

    Enter the number of orders:
    Enter all the orders:
    Enter number of threads to process the data:
    Jan — 3
    Feb — 4
    Mar — 3
    Apr — 3
    May — 4
    Jun — 3
    Jul — 1
    Aug — 1
    Nov — 1
    Dec – 1

    1. amina shadan says:

      Hi Sam,

      Did u get the program out for this one. I need the program code for the same question. Can you plz share the program code with me.

    2. Anu says:

      i also need answer for this program.

    3. KK says:

      Hi Sam- I am new to JAVA and learning , Can you please post the answer for the above listed Thread question working code? It will really helpful for me to understand. Thanks in Advance.

    4. Mijizz says:

      I want the program code for this question. Can u plz share with me.

      1. Vineeth says:

        I want the code for this question .Can u Please give?

  3. Rahul says:

    I think at 6th line it should be
    MyThread – START t3
    and 8th line
    MyThread – START t4

    as you are printing their name(.getName()) specified while calling constructor.
    Correct me pls if i’m wrong

    1. Varun says:

      Yes, you are right.

  4. Tasfi says:

    plz help me

    Which one is the best way to write tread ?
    extend/ implement

    1. Soniya Vijay says:

      As suggested in the above tutorial,

      By using implement extend Thread we are stopping that class to further use the inheritance feature. So if we want to apply inheritance we should implement Runnable to make threads

    2. Omkar says:

      Implement is the best way because using interface can allow us to extend thread using other classes also like serialisable, clonable etc.

    3. CHENCHUKUMAR S says:

      implementes is best choice

    4. ghanshyam Nagpure says:

      There is not much difference, but if you extend thread class then you cant extend any other class as Java does not support multiple inheritance. Hence you should use implementing runnable interface if you want to extend other class.

  5. Sudhansu says:

    Java provides two ways to create a thread programmatically.??
    Not expecting this kind of statements from JDev.
    U can create a thread by only one way, create Thread class object(Directly or indirectly)
    But when you create a thread it will execute a task, and the task you can define by run() method.
    Which can be 2 ways, extend a class or implement runnable…

    1. Pankaj says:

      That’s what I meant by two ways – Runnable implementation or extend Thread class.

  6. sambasiva says:

    Useful information.

  7. reader says:

    1:extends thread;2:implements runnable;3:implements callable;

  8. lzf1738 says:

    It is a wonderful article. Thank you

  9. jyothi says:

    very good post

  10. lamba says:

    If your class provides more functionality rather than just running as Thread, you should implement Runnable interface to provide a way to run it as Thread. If your class only goal is to run as Thread, you can extend Thread class.

    I think something is wrong in the above statement.

    1. Pallavi says:

      NO, its right statement, If our class have more functionality, that means may be we have to extend some other classes/interfaces also. So if we extend Thread class then we can’t extend other classes, but by implementing runnable we can extend/implement multiple interfaces.

  11. Bhavesh Modi says:

    Nice post

  12. Ankita says:

    Hi Pankaj ,

    did you write any article on read-write locking (reader Preference and writer preference) ?


  13. Vishal Sudheer says:

    Hello Sir,
    You did not mention anything about closing the database connection. Do we have to close the database connection after doDBProcessing(); or in the main function?

    Thanks and regards.


  14. anna says:

    very useful

Comments are closed.

Generic selectors
Exact matches only
Search in title
Search in content