Wednesday, October 23, 2024

How to Implement Thread in Java with Example

How to implement Thread in Java
In my opinion, Thread is one of the most important features of the Java programming language which helped it to become the most popular programming language. I remember, when I first started learning Java in one of the programming classes in India how important Thread was a portrait and how much emphasis is given on a clear understanding of multi-threading. It’s still popular and one of most sought after skills in Java programmer because writing concurrent and multi-threaded applications in Java is challenging, despite Java providing excellent support at language level using synchronized and volatile keyword.


The main problem with using multiple threads and writing multi-threaded code is issues related to concurrency e.g. deadlock, livelock, race conditions, etc, It takes a lot of effort to implement multi-threading correctly in Java application.

In this core Java tutorial I will share my experience on a different way of implementing Thread in Java;  By the way difference between Thread and Runnable in Java is also a very common core Java interview question and asked mostly during junior level Java interviews.

After reading this tutorial, you will not only be able to create and start a thread but also be able to answer what is a difference in two ways of implementing thread in Java, by implementing the Runnable interface or by extending the Thread class.

By the way, if you are serious about mastering Java multi-threading and concurrency then I also suggest you take a look at these Java Multithreading courses. They are great resources to learn and improve your multithreading and concurrency skills. 




How to make Thread in Java?

There are two ways of implementing threading in Java

1) By extending java.lang.Thread class, or

2) By implementing java.lang.Runnable interface.


Before we go into implementation details I just like to cover when we use Thread in Java?  So we use thread if we want some part of code is executed parallel and we put that code inside run() method of either Thread class or Runnable interface.


Actually public void run() method is defined in the Runnable interface and since java.lang.Thread class implements Runnable interface it gets this method automatically. 

I remember by first Java multi threading example which was an animation program where multiple threads were used in Applet to create animation of words falling from top left, middle and top right of the page. 

That was pretty exciting at that time because till then I only know program which takes input from command prompt and print output on command prompt.



Java Thread Tutorial and Example

So now the interview question  which way of implementing Thread is better? Extending Thread class or implementing Runnable method?

In my opinion implementing Runnable is better because in Java we can only extend one class so if we extend Thread class we can not extend any other class while by implementing Runnable interface we still have that option open with us.

Second reason which make sense to me is more on OOPS concept according to OOPS if we extend a class we provide some new feature or functionality , So if the purpose is just to use the run() method to define code its better to use Runnable interface. 

If you are still not convince on why implementing Runnable is better than extending the Thread class for creating threads in Java, I think it's time you should read this article.

How to create Thread in Java



So first step is complete, you have implemented thread by now. Next step is to actually create object of the thread class and start it. 

This is will create a separate path of execution parallel to main thread. Java thread is state based so it remains in predefined state at any given time and state transition occurs by calling different thread method. 

So, when you create object of your class which has implemented Runnable or extended Thread, you just create an object of Thread class, Thread will not start until you call the start() method of java.lang.Thread class. 

This is shown clearly in above thread state transition diagram in Java. It is now in NEW state, when we call start() method Java Virtual machine execute run() method of that Thread class it goes into RUNNABLE state. 

Now, it's up to the thread scheduler to assign CPU to this thread. From here on it can either complete its execution and go to TERMINATED state or can go into WAITING, TIMED WAITING, and BLOCKED state. 

By the way, if you notice, when we call the start() method, it eventually calls the run() method, can anybody guess what will happen if we call the run() method directly instead of calling the start() method?


That another popular multi-threading interview question and answer is simple there would be no Error or Exception run() method will simply be executed in the same Thread and new Thread will not be created. 

Another follow up question would be what will happen if you call start() method twice in same Thread object e.g.

mythread.start(); 
mythread.start(); //this line will throw IllegalThreadStateException


//implementing Thread by extending Thread class
 public class MyThread extends Thread{       

   public void run(){
      System.out.println(" Thread Running " + Thread.currentThread().getName());
   }
 }


//implementing Thread by implementing Runnable interface

public class MyRunnable implements Runnable{         

    public void run(){
       System.out.println(" Create Thread " + Thread.currentThread().getName());
    }

 }


//starting Thread in Java
Thread mythread = new MyThread(); //Thread created not started
mythread.setName("T1");
Thread myrunnable = new Thread(new MyRunnable(),"T2"); //Thread created       

mythread.start(); //Thread started now but not running 
myrunnable.start();

Bonus Tip

TIP1: It’s not guaranteed that thread mythread will start before thread myrunnable it depends upon Thread scheduler.

TIP2: Thread will be said to go on dead state once execution of run() method finished and you can not start that thread again.


Other Java Thread tutorial from Javarevisited Blog
  1. Why wait and notify method must be called in synchronized context? (see here)
  2. How Synchronization works in Java? (read more)
  3. How to write Thread-safe class in Java? (read here)
  4. 50 Thread Questions from Java Interview for Experienced (check here)
  5. How to Stop Thread in Java? (see here)
  6. Inter thread communication in Java (read more)
  7. Difference between Daemon and User thread in Java (read here)
  8. How to create Thread Pool in Java (read here)
  9. How to check if a Thread holds an Object Lock? (check here)
  10. Difference between wait(), sleep() and yield() in Java (read more)
  11. How to use ThreadLocal variable in Java? (read here)

13 comments:

  1. Hi Sandeep,
    Thanks Sandeep. regarding your question can you please clarify what does faster means here , I am not really sure if you talking about class binding or something else ?

    Thanks
    Javin

    ReplyDelete
  2. I meant that extending from class is good in terms of performance or implementing Runnable.
    Say I have 50 threads created using Thread class in program1 and 50 using Runnable in Program2. Which is expected to be fast if everything else is same.

    ReplyDelete
  3. You should never extend Thread. It's simply a misconception.
    Better is to use a ThreadPool with java.util.concurrent.*

    ReplyDelete
  4. @Sandeep

    I cannot imagine anybody asking this question seriously, I suppose that expected answer is something like "I would use Threadpool/Executors in first place"...

    ReplyDelete
  5. I would be surprise if there is performance difference between JUST Runnable or extend Thread, please let me know if it is not.

    I guess the question is actually about the possible of using thread pool with same logic.

    ReplyDelete
  6. Hi CARFIELD,

    Thread pool is obviously better choice especially when JAVA 5 provides Executor framework and having Runnable task works well with concept of worker threads.

    Thanks
    Javin

    ReplyDelete
  7. can we build 2 thread connected to other in the same calss???????????!!!!111 thanks

    ReplyDelete
  8. @Anonymous, yes you can have multiple thread started from one Thread. Class is just holder for code and logical representation of Object. What is important is that you can share same Runnable implementation(which is a class ) between multiple threads also.

    ReplyDelete
  9. Hi Dude, Executor framework which is available from Java 5 onwards is better choice for creating threads and managing them in Java Program Instead of creating threads directly by implementing either Runnable or Callable interface. What is your thought ?

    ReplyDelete
  10. in my interface program i am having 2 methods i need to execute only one method how can i execute it

    ReplyDelete
  11. what will be the class of Runnble interface

    ReplyDelete
  12. WHY DID UUSED INTERFACE IN THREAD?

    ReplyDelete
  13. Plz give me a proper ans for the que two different ways used to implement threading in java

    ReplyDelete