blog

Home / DeveloperSection / Blogs / Threads in Java

Threads in Java

Prateek sharma 1479 29-Jan-2018

A thread is a lightweight independent process. Threading allows multiple processes to exist in one. Most of the modern operating system supports threads. Threads are independent, have concurrent execution, local variables, and its own stack.  

There can exist multiple threads within a process which means that these threads will have same memory address space, this will allow a thread to share information with each other. It must be taken care that threads do not interfere with each other.

Why use threads?

Reasons for using the thread as they help to:

  1. Make UI more responsive.
  2. Gives the advantage of a multiprocessor system.
  3. Makes the modeling easy
  4. Perform asynchronous or background processing.

A simple example of a thread in Java by extending thread class. 

class Multi extends Thread{ 

public void run(){
System.out.println("thread is running...");
}
public static void main(String args[]){
Multi t1=new Multi();
t1.start();
 }
}

public void run(): is used to perform some action for a thread.

Threads can also be implemented using Runnable interface. Following is the example

class Multi3 implements Runnable{ 

public void run(){
System.out.println("thread is running...");
}
public static void main(String args[]){
Multi3 m1=new Multi3();
Thread t1 =new Thread(m1);
t1.start();
}
}



Updated 29-Jan-2018

Leave Comment

Comments

Liked By