Friday, May 24, 2024
HomeJavaTips on how to Implement Thread in Java with Instance

Tips on how to Implement Thread in Java with Instance


Tips on how to implement Thread in Java
In my view, Thread is among the most vital options of the Java programming language which helped it to develop into the most well-liked programming language. I keep in mind, once I first began studying Java in one of many programming lessons in India how vital Thread was a portrait and the way a lot emphasis is given on a transparent understanding of multi-threading. It’s nonetheless fashionable and considered one of most wanted expertise in Java programmer as a result of writing concurrent and multi-threaded purposes in Java is difficult, regardless of Java offering wonderful assist at language degree utilizing synchronized and unstable key phrase.

The principle downside with utilizing a number of threads and writing multi-threaded code is points associated to concurrency e.g. impasse, livelock, race circumstances, and many others, It takes a whole lot of effort to implement multi-threading appropriately in Java software.

On this core Java tutorial I’ll share my expertise on a distinct means of implementing Thread in Java;  By the best way distinction between Thread and Runnable in Java can be a quite common core Java interview query and requested principally throughout junior degree Java interviews.

After studying this tutorial, you’ll not solely have the ability to create and begin a thread but additionally have the ability to reply what’s a distinction in two methods of implementing thread in Java, by implementing the Runnable interface or by extending the Thread class.

By the best way, if you’re critical about mastering Java multi-threading and concurrency then I additionally counsel you check out these Java Multithreading programs. They’re nice assets to be taught and enhance your multithreading and concurrency expertise. 

Tips on how to make Thread in Java?

There are two methods of implementing threading in Java

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

2) By implementing java.lang.Runnable interface.

Earlier than we go into implementation particulars I identical to to cowl once we use Thread in Java?  So we use thread if we wish some a part of code is executed parallel and we put that code inside run() technique of both Thread class or Runnable interface.

Truly public void run() technique is outlined within the Runnable interface and since java.lang.Thread class implements Runnable interface it will get this technique robotically. I keep in mind by first Java multi threading instance which was an animation program the place a number of threads had been utilized in Applet to create animation of phrases falling from prime left, center and prime proper of the web page. That was fairly thrilling at the moment as a result of until then I solely know program which takes enter from command immediate and print output on command immediate.

Java Thread Tutorial and Instance

So now the interview query  which means of implementing Thread is healthier? Extending Thread class or implementing Runnable technique?

In my view implementing Runnable is healthier as a result of in Java we are able to solely lengthen one class so if we lengthen Thread class we can’t lengthen another class whereas by implementing Runnable interface we nonetheless have that choice open with us.

Second purpose which make sense to me is extra on OOPS idea in keeping with OOPS if we lengthen a category we offer some new function or performance , So if the aim is simply to make use of the run() technique to outline code its higher to make use of Runnable interface. 

If you’re nonetheless not persuade on why implementing Runnable is healthier than extending the Thread class for creating threads in Java, I believe it is time it’s best to learn this article.

How to create Thread in Java

So first step is full, you may have applied thread by now. Subsequent step is to really create object of the thread class and begin it. That is will create a separate path of execution parallel to important thread. Java thread is state based mostly so it stays in predefined state at any given time and state transition happens by calling totally different thread technique. 

So, if you create object of your class which has applied Runnable or prolonged Thread, you simply create an object of Thread class, Thread won’t begin till you name the begin() technique of java.lang.Thread class. 

That is proven clearly in above thread state transition diagram in Java. It’s now in NEW state, once we name begin() technique Java Digital machine execute run() technique of that Thread class it goes into RUNNABLE state. 

Now, it is as much as the thread scheduler to assign CPU to this thread. From right here on it may possibly both full its execution and go to TERMINATED state or can go into WAITING, TIMED WAITING, and BLOCKED state. 

By the best way, for those who discover, once we name the begin() technique, it will definitely calls the run() technique, can anyone guess what is going to occur if we name the run() technique instantly as a substitute of calling the beginning() technique?

That one other fashionable multi-threading interview query and reply is straightforward there can be no Error or Exception run() technique will merely be executed in the identical Thread and new Thread won’t be created. One other observe up query can be what is going to occur for those who name begin() technique twice in identical Thread object e.g.

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


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

   public void run(){
      System.out.println(" Thread Working " + 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());
    }

 }


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

mythread.begin(); //Thread began now however not operating 
myrunnable.begin();

Bonus Tip

TIP1: It’s not assured that thread mythread will begin earlier than thread myrunnable it relies upon upon Thread scheduler.

TIP2: Thread can be stated to go on useless state as soon as execution of run() technique completed and you can’t begin that thread once more.

Different Java Thread tutorial from Javarevisited Weblog

  1. Why wait and notify technique should be known as in synchronized context? (see right here)
  2. How Synchronization works in Java? (learn extra)
  3. Tips on how to write Thread-safe class in Java? (learn right here)
  4. 50 Thread Questions from Java Interview for Skilled (examine right here)
  5. Tips on how to Cease Thread in Java? (see right here)
  6. Inter thread communication in Java (learn extra)
  7. Distinction between Daemon and Person thread in Java (learn right here)
  8. Tips on how to create Thread Pool in Java (learn right here)
  9. Tips on how to examine if a Thread holds an Object Lock? (examine right here)
  10. Distinction between wait(), sleep() and yield() in Java (learn extra)
  11. Tips on how to use ThreadLocal variable in Java? (learn right here)



RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments