Thread, The real worker

what is thread in java
thread is an independent path of execution within a program. Many threads can run concurrently within a program. Every thread in Java is a the java.lang.Thread. 
A thread can be in one of the five states. According to sun, there is only 4 states in thread life cycle in java new, runnable, non-runnable and terminated. There is no running state.But for better understanding the threads, we are explaining it in the 5 states.The life cycle of the thread in java is controlled by JVM. The java thread states are as follows:
  1. New
  2. Runnable
  3. Running
  4. Non-Runnable (Blocked)
  5. Terminated


An application that creates an instance of Thread must provide the code that will run in that thread. There are two ways to do this:
  • Provide a Runnable object. The Runnable interface defines a single method, run, meant to contain the code executed in the thread. The Runnable object is passed to the Threadconstructor, as in the HelloRunnable example:
  1. public class HelloRunnable implements Runnable {
  2. public void run() {
  3. System.out.println("Hello from a thread!");
  4. }
  5. public static void main(String args[]) {
  6. (new Thread(new HelloRunnable())).start();
  7. }
  8. }
  • Subclass Thread. The Thread class itself implements Runnable, though its run method does nothing. An application can subclass Thread, providing its own implementation of run, as in the HelloThreadexample:
  1. public class HelloThread extends Thread {
  2. public void run() {
  3. System.out.println("Hello from a thread!");
  4. }
  5. public static void main(String args[]) {
  6. (new HelloThread()).start();
  7. }
  8. }
Notice that both examples invoke Thread.start in order to start the new thread.
Which of these idioms should you use? The first idiom, which employs a Runnable object, is more general, because the Runnable object can subclass a class other than Thread. The second idiom is easier to use in simple applications, but is limited by the fact that your task class must be a descendant of Thread. This lesson focuses on the first approach, which separates the Runnable task from the Thread object that executes the task. Not only is this approach more flexible, but it is applicable to the high-level thread management APIs covered later.
The Thread class defines a number of methods useful for thread management. These include static methods, which provide information about, or affect the status of, the thread invoking the method. The other methods are invoked from other threads involved in managing the thread and Thread object.

Check here the gist behind thread.

0 comments:

Post a Comment

My Instagram