Senin, 17 Februari 2014

How to Implement Thread in Java with Example



How to implement Thread in Java

In my opinion Thread is one of the most important feature of 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 class on India how important Thread was portrait and how much emphasis given on clear understanding of multi-threading. It’s still popular and one of most sought after skill in Java programmer because writing concurrent and multi-threaded application in Java is challenging, despite Java providing excellent support at language level using synchronized and volatile keyword. 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 lot of effort to implement multi-threading correctly in Java application. In this core Java tutorial I will share my experience on 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 interview. After reading this tutorial, you will not only able to create and start thread but also able to answer what is difference in two ways of implementing thread in Java, by implementing Runnable interface or by extending Thread class.








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 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 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 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 RUNNBLE state. Now, it's upto 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 start() method, it eventually calls run() method, can anybody guess what will happen if we call the run() method directly instead of calling 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)

























Source:http://javarevisited.blogspot.com/2011/02/how-to-implement-thread-in-java.html

Tidak ada komentar:

Posting Komentar