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.

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.

Comments

  1. 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:
    24
    Enter all the orders:
    45512252,12/04/2015
    45512522,05/06/2015
    45254822,03/05/2015
    45221522,20/07/2015
    45227855,25/01/2015
    45225851,13/02/2015
    45221545,18/08/2015
    45222124,20/12/2015
    45232785,06/02/2016
    45235654,05/03/2016
    45235451,15/05/2016
    45236545,20/05/2016
    45237854,22/06/2016
    45237864,14/04/2016
    45237912,13/03/2016
    45238945,16/04/2016
    45238955,15/01/2017
    45239454,02/01/2017
    45239551,06/02/2017
    45239560,18/05/2017
    45239789,25/06/2017
    45239840,12/03/2017
    45239856,17/02/2017
    45245220,15/11/2017
    Enter number of threads to process the data:
    2
    Jan — 3
    Feb — 4
    Mar — 3
    Apr — 3
    May — 4
    Jun — 3
    Jul — 1
    Aug — 1
    Nov — 1
    Dec – 1

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

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

  4. Sudhansu says:

    Java provides two ways to create a thread programmatically.??
    Really?
    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.

  5. sambasiva says:

    Useful information.

  6. reader says:

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

  7. lzf1738 says:

    It is a wonderful article. Thank you

  8. jyothi says:

    very good post

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

  10. Bhavesh Modi says:

    Nice post

  11. Ankita says:

    Hi Pankaj ,

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

    Ankita

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

    Vishal

  13. anna says:

    very useful

Leave a Reply

Your email address will not be published. Required fields are marked *

close
Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages