Threads in JAVA

A Threads is a separate path of execution within a program. Every thread in Java is created and controlled by the java.lang.Thread class.

there are two type  of thead -  user thread and daemon thread. When we start an application, main is the first user thread created and we can create multiple user threads as well as daemon threads. When all the user threads are executed, JVM terminates the program.

Note:-
Threads are lightweight compared to processes
Threads share the same address space and therefore can share both data and code

Context switching between threads is usually less expensive than between processes

Threads can be use in two way:-
   Extend the java.lang.Thread class.
   Implement the Runnable interface

1.Implement the Runnable:-
A class implements the Runnable interface, providing the run() method that will be executed by the thread. An object of this class is a Runnable object.

class DemoThread implements Runnable
{
 public void run()
 {
  System.out.println("thread started running..");
 }
}

class MyThreadDemo
{
 public static void main( String args[] )
 {
  DemoThread mt = new DemoThread();
  Thread t = new Thread(mt);
  t.start();
 }
}


2.Extend the java.lang.Thread class

his is another way to create a thread by a new class that extends Thread class and create an instance of that class. The extending class must override run() method which is the entry point of new thread.

class DemoThread extends Thread
{
 public void run()
 {
  System.out.println("Concurrent thread started running..");
 }
}

class MyThreadDemo
{
 public static void main( String args[] )
 {
  DemoThread dt = new  DemoThread();
  dt.start();
 }
}

In above program if we directly call run() method, without using start() method,

public static void main( String args[] )
{
 DemoThread dt = new DemoThread();
 dt.run();
}

Not:- thread cannot be started twice



 dt.run();
 dt.run();