THREADS IN JAVA
Thread:
- A thread is a separate component of a process that can run on its own.
- Thread is a light weight process (LWP).
- Part of a program in execution.
Multi-threading:
- Executing more than one thread i.e program at one time is Multi-Threading.
Advantages:
1. Threads share common memory.
2. Context switching between threads takes less time than process.
3. Multi-threading is used in games, animation, etc…
4. Threads are independence.
Methods of Thread class:
1. start()
2. run()
3. sleep()
4. join()
5. getName()
6. getPriority()
7. yield()
Life Cycle of Thread:
1. New
2. Runnable
3. Running
4. Blocked
5. Dead state
Creating Thread are two methods:
1. Extending Thread class
2. Implementing Runnable interface
Extends Thread
Example:1
Class T1 extends Thread
{
Public void run()
{
for (int i=1; i<=3; i++)
{
System.out.println(“Thread 1:” +i);
}
}
}
Class T2 extends Thread
{
Public void run()
{
for (int i=1; i<=3; i++)
{
System.out.println(“Thread 2:” +i);
}
}
}
Class Threaddemo
{
public static void main(String args[])
{
T1 Obj1 = new T1();
Obj1.start();
T2 Obj2 = new T2();
Obj2.start();
}
}
Output:
Thread 1: 1
Thread 1: 2
Thread 2: 1
Thread 2: 2
Thread 3: 3
Thread 3: 3
Implementation Runable:
Example:2
Class T1 implements Runnable
{
Public void run()
{
for(int i=1; i<=3; i++)
{
System.out.println(“Thread X: “ +i);
}
}
public static void main(String args[])
{
T1 ob = new T1();
Thread t = new Thread(ob);
t.start();
}
}
Output:
Thread X: 1
Thread X: 2
Thread X: 3
Example:3
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();
}
}
Output:
thread is running...