What is a thread?
A thread is a lightweight process. It is usually refer to as the path of execution. A Program that contains two or more parts that run simultaneously—each part of such a program is refer to as a thread.
What is multithreading?
- It is refer to two or more than two threads running concurrently.
- It is the built in feature of Java.
- The specialized form of multithreading is multitasking.
- With the help of multithreading we can create effective programs with optimum utilization of CPU, because idle time is minimum.
How to create threads?
There are two ways of creating threads in Java—
1. by implementing Runnable Interface.
2. By extending the Thread class.
1. by implementing Runnable Interface.
2. By extending the Thread class.
Example:
A simple program of creating a thread by implementing
package
javaeffect;
public
class NewThread {
public static void main(String[] args) {
DemoThread d = new DemoThread();
Thread t = new Thread(d);
t.start();
}
}
class
DemoThread implements Runnable
{
@Override
public void run() {
for(int i=0; i<5; i++)
{
System.out.println("thread 1
: " + i);
}
}
}
|
Explanation:
Run ()—this is the method of Runnable Interface and this is the entry point for the thread.
Start ()—start is the method which is used to start a thread by calling its run method.
Object of DemoThread class—the object is created for the DemoThread class and its reference is passed to the thread.
@Override—this is an annotation.
Start ()—start is the method which is used to start a thread by calling its run method.
Object of DemoThread class—the object is created for the DemoThread class and its reference is passed to the thread.
@Override—this is an annotation.
Example:
Second method for creating a thread by extending Thread class.
package javaeffect;
public class DemoThread1 extends Thread {
public void run(){
System.out.println("this thread is
running using Thread class");
}
public static void main(String[] args) {
DemoThread1 d1 = new
DemoThread1();
Thread t1 = new Thread(d1);
t1.start();
}
}
|
Life cycle of a thread:
First, a thread class object is created----Thread t = new Thread ();
Once the start () method is called, the thread is in Runnable state. The thread in Runnable state may or may not be running.
After this the thread is in running state. When the run () method is called by start () method.
In middle a thread can be suspended, blocked etc.
Once the start () method is called, the thread is in Runnable state. The thread in Runnable state may or may not be running.
After this the thread is in running state. When the run () method is called by start () method.
In middle a thread can be suspended, blocked etc.
Last is the Termination state, where the execution completes.
Life cycle of Thread:
If you find this article helpful, feel free to share on facebook, twitter and Google plus.
Tags
Java