In this tutorial we will discuss about Java Thread.
In this tutorial we will discuss about Java Thread.In this tutorial we will discuss about Java Thread.
Java Thread :
A thread is light weight java program.JVM permits you to have multiple threads for concurrent execution. Each thread has priority. You can also set priority to threads. Thread having higher priority will execute first and then the other thread having priority less than the higher one.
Life cycle of thread :
Diagram - Here is pictorial representation of thread life cycle.
State of Thread Life cycle -
Thread Priorities: Thread having higher priority, execute
first. Java priorities ranges from MAX_PRIORITY (constant
value 10) to
MIN_PRIORITY (constant value 1).
Thread class provides you 3 priority -
MAX_PRIORITY : It is maximum priority that a thread hold.
MIN_PRIORITY : It is minimum priority that a thread hold.
NORM_PRIORITY : It is default priority that a thread hold.
Example :
public class SimpleThread extends Thread { private int c = 3; private static int threadC = 0; public SimpleThread() { super("" + ++threadC); // Store the thread name start(); } public String toString() { return "Thread"+getName() + ": " + c; } public void run() { while(true) { System.out.println(this); if(--c == 0) return; } } public static void main(String[] args) { for(int i = 0; i <3; i++) new SimpleThread(); } }
Output :
Thread1: 3 Thread1: 2 Thread1: 1 Thread2: 3 Thread2: 2 Thread2: 1 Thread3: 3 Thread3: 2 Thread3: 1