Tutorial

Java Thread Example

Published on August 3, 2022
author

Pankaj

Java Thread Example

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

Process

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

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 {

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

    private void doDBProcessing() throws InterruptedException {
        Thread.sleep(5000);
    }

}

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) {
        super(name);
    }

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

    private void doDBProcessing() throws InterruptedException {
        Thread.sleep(5000);
    }
    
}

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");
        t1.start();
        t2.start();
        System.out.println("Runnable Threads has been started");
        Thread t3 = new MyThread("t3");
        Thread t4 = new MyThread("t4");
        System.out.println("Starting MyThreads");
        t3.start();
        t4.start();
        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.

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Learn more about our products

About the authors
Default avatar
Pankaj

author

While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.

Still looking for an answer?

Ask a questionSearch for more help

Was this helpful?
 
JournalDev
DigitalOcean Employee
DigitalOcean Employee badge
September 18, 2014

very useful

- anna

    JournalDev
    DigitalOcean Employee
    DigitalOcean Employee badge
    December 10, 2014

    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. Vishal

    - Vishal Sudheer

      JournalDev
      DigitalOcean Employee
      DigitalOcean Employee badge
      April 4, 2015

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

      - Ankita

        JournalDev
        DigitalOcean Employee
        DigitalOcean Employee badge
        May 26, 2015

        Nice post

        - Bhavesh Modi

          JournalDev
          DigitalOcean Employee
          DigitalOcean Employee badge
          October 18, 2015

          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.

          - lamba

            JournalDev
            DigitalOcean Employee
            DigitalOcean Employee badge
            June 17, 2016

            very good post

            - jyothi

              JournalDev
              DigitalOcean Employee
              DigitalOcean Employee badge
              July 14, 2016

              It is a wonderful article. Thank you

              - lzf1738

                JournalDev
                DigitalOcean Employee
                DigitalOcean Employee badge
                October 6, 2016

                thanks

                - LJ

                  JournalDev
                  DigitalOcean Employee
                  DigitalOcean Employee badge
                  October 14, 2016

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

                  - reader

                    JournalDev
                    DigitalOcean Employee
                    DigitalOcean Employee badge
                    December 21, 2016

                    Useful information.

                    - sambasiva

                      Try DigitalOcean for free

                      Click below to sign up and get $200 of credit to try our products over 60 days!

                      Sign up

                      Join the Tech Talk
                      Success! Thank you! Please check your email for further details.

                      Please complete your information!

                      Become a contributor for community

                      Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.

                      DigitalOcean Documentation

                      Full documentation for every DigitalOcean product.

                      Resources for startups and SMBs

                      The Wave has everything you need to know about building a business, from raising funding to marketing your product.

                      Get our newsletter

                      Stay up to date by signing up for DigitalOcean’s Infrastructure as a Newsletter.

                      New accounts only. By submitting your email you agree to our Privacy Policy

                      The developer cloud

                      Scale up as you grow — whether you're running one virtual machine or ten thousand.

                      Get started for free

                      Sign up and get $200 in credit for your first 60 days with DigitalOcean.*

                      *This promotional offer applies to new accounts only.