Thursday, August 15, 2013

Understanding Threads in Java

A Thread is an independent sequential path of execution within a process / program. Multiple threads can run concurrently in a program . Threads are lightweight as compared to the process as at runtime , they exist in a common memory space and can share process's resources like  data and code.

Threads make the runtime environment asynchronous , allowing different tasks to be performed concurrently . In Java , a thread is represented and controlled by an object of class java.lang.Thread.

main() method is executed as a Thread.
When an application ( or a program ) is run, a user thread is created to execute the main() method of the application. This thread is called main thread.

Thread Creation :
A thread in java is represented by an object of class java.lang.Thread and can be created in two ways :

1. Implementing java.lang.Runnable interface.
The Runnable interface defines a method run() that contains the code that is to be executed in a thread. Lets create a thread that says " Hello User ".

public class MyRunnable implements Runnable {

 // Statements defined in run() methods are executed as a thread.
 public void run(){
  System.out.println("Hello User");
 }

 public static void main(String[] args) {             
  // Creating an object of Thread class and passing a Runnable in its constructor.
  Thread thread = new Thread(new MyRunnable());

  // Starting a thread.
  thread.start();
 }
}
 
    
2. Extending java.lang.Thread class.
Another way to create a thread is by extending Thread class  and override the run() method .The Thread class itself implements Runnable but its run() method does nothing.

public class MyThread extends Thread {

 public void run() {
  System.out.println("Hello User");
 }

 public static void main(String[] args) {
  new MyThread().start();
 }
}

No comments :

Post a Comment