Multithreading
A program can be divided into a number of small processes. Each process can be addressed as a
single thread. (Thread is a light weight process, which share resources of the main thread)
Multithreading programs contain two or more threads that can run concurrently. This means that a
single program can perform two or more tasks simultaneously.
Example – one thread writing or typing contents to MS-Word, other thread checking spellings.
Main Thread – Even if you don’t create any thread in your program, a thread called main is still created.
Life cycle of a thread
Start() Ready
New
Resume
Dispatch Blocked
Yield
Exit Running Sleep
Completed
Methods of Multithreading in Java
1. By extending Thread class
2. By implementing Runnable Interface
1. Extending Thread class
Example
class display extends Thread
{
String msg;
display(String s)
{
msg=s;
}
public void run()
{
for(i=0;i<3;i++)
[Link](i);
}
}
class test
{
public static void main(String a[])
{
display d1=new display(“Hello”);
display d2=new display(“World”);
[Link]();
[Link]();
}}
Using Runnable Interface
class display implements Runnable
{
String msg;
display(String s)
{
msg=s;
}
public void run()
{
for(i=0;i<3;i++)
[Link](i);
}
}
class test
{
public static void main(String a[])
{
display d1=new display(“Hello”);
display d2=new display(“World”);
Thread t1=new Thread(d1);
Thread t2=new Thread(t2);
[Link]();
[Link]();
}
}
Note – If we call run() method instead of start() method the thread will not be initialized and multithreading will not
happen.
Using sleep() Method
We can block a thread for some time using sleep method. This method raise an exception called as
InterruptedException.
Syntax – sleep(time in ms)
Example-
class display extends Thread
{
public void run()
{
try
{
for(i=0;i<3;i++)
{
[Link](i);
sleep(500); //thread block for 500 ms.
}
}catch(InterruptedException e) {[Link](“Thread is interrupted”);}
}
class test
{
public static void main(String a[])
{
display d1=new display(“Hello”);
display d2=new display(“World”);
[Link]();
[Link]();
}
}