What is 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?
1. by implementing Runnable Interface.
2. By extending the Thread class.
Example:
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:
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:
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:
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.
0 comments:
Post a Comment