Google News
logo
Java - Create Thread
Create Thread
1) Thread is nothing but separate path of sequential execution. 

2) The independent execution technical name is called thread. 

3) Whenever different parts of the program executed simultaneously that each and every part is called thread. 

4) The thread is light weight process because whenever we are creating thread it is not occupying the separate memory it uses the same memory. Whenever the memory is shared means it is not consuming more memory. 

5) Executing more than one thread a time is called multithreading.
Single threaded program
class Test 
{ 
public static void main(String[] args) 
{ 
System.out.println("Hello World!"); 
System.out.println("hi freetimelearn");
} 
}
Output :
Hello World!
hi freetimelearn
Thread Information
import java.io.*; 
import java.util.*; 
class Test 
{ 
public static void main(String[] args) 
{ 
Thread t=Thread.currentThread(); 
System.out.println("currrent thread information is : "+t);
System.out.println("currrent thread priority is : "+t.getPriority());
System.out.println("currrent thread name is : "+t.getName()); 
} 
}
Output :
currrent thread information is : Thread[main,5,main] currrent thread priority is : 5 currrent thread name is : main
The main important application areas of the multithreading are
1. Developing video games 

2. Implementing multimedia graphics. 

3. Developing animations 
There are two different ways to create a thread isavilable
1) Create class that extending standered java.lang.Thread Class
2) Create class that Implementing java.lang.Runnable interface
First approach to create thread extending Thread class:-
Step 1:-
Creates a class that is extend by Thread classes and override the run() method
class MyThread extends Thread
{
public void run()
{
System.out.println("business logic of the thread");
System.out.println("body of the thread");
}
};
Step 2:-
Create a Thread object
MyThread t=new MyThread();
Step 3:-
Starts the execution of a thread.
t.start();
Thread program
class MyThread extends Thread 
{ 
public void run() 
{ 
System.out.println("freetimelearn"); 
System.out.println("body of the thread"); 
} 
}; 
class ThreadDemo 
{ 
public static void main(String[] args) 
{ 
MyThread t=new MyThread(); 
t.start(); 
} 
}
Output :
freetimelearn
body of the thread
Note :-
1) Whenever we are calling t.start() method the JVM search for the start() in the MyThread class but the start() method is not present in the MyThread class so JVM goes to parent class called Thread class and search for the start() method.
2) In the Thread class start() method is available hence JVM is executing start() method.
3) Whenever the thread class start() that start() is responsible person to call run() method.
4) Finally the run() automatically executed whenever we are calling start() method.
5) Whenever we are giving a chance to the Thread class start() method then only a new thread will be created.