Concept of Thread refer to running many processes(subprograms) concurrently
within a Main program.
As simple illustration.
If COOKING a dish is the Main program.
Within it, Heating Oil and Cutting Vegetables are independent tasks.
There is no need to wait to cut vegetables till Oil is heated.
Theses two tasks can be performed concurrently by assigning them two people.
Same thing can be done in java by assigning the tasks to two threads.
We will use the above example and write a Java program with
COOKING as a the Main program and
HEATING OIL and CUTTING VEGETABLE as two threads running concurrently
within the Main program.
In Java, Thread can be created in two ways.
1. Using the RUNNABLE interface
2. By extending THREAD class.
This programs uses extended THREAD class.
The classes overrides run() method.
run() method contains content of the thread.
Threads end when run() method is completed.
/* HeaingOil thread class*/
class HeatingOil extends Thread{
int HOcount;
public void run() {
while(HOcount <= 5){
try{
System.out.println("Mts "+(++HOcount) +"- Heating Oil");
Thread.sleep(1000);
} catch (InterruptedException ie) {
System.out.println("Exception in thread: "+ie.getMessage());
}
}
}
}
/* CuttingVegetable Thread class */
class CuttingVegetable extends Thread{
int VCcount;
public void run() {
while(VCcount <= 5){
try{
System.out.println("Mts "+(++VCcount) +"- Cutting Veg.");
Thread.sleep(1000);
} catch (InterruptedException ie) {
System.out.println("Exception in thread: "+ie.getMessage());
}
}
}
}
/* Main Program */
public class Cooking {
public static void main(String[] args) {
HeatingOil hot=new HeatingOil(); // Object instances of thread classes
CuttingVegetable cvt = new CuttingVegetable();
hot.start(); // Starting the threads
cvt.start();
while (cvt.isAlive() && hot.isAlive()){ //Loops till threads ends
try{
Thread.sleep(1000);
} catch (InterruptedException ie){
System.out.println("Exception in main thread: "+ie.getMessage());
}
}
System.out.println("CUTTING VEG. IS OVER");
System.out.println("HEATING OIL IS OVER");
System.out.println("Main Program COOKING proceeds...");
}
}
Output -
run:
Mts 1- Heating Oil
Mts 1- Cutting Veg.
Mts 2- Heating Oil
Mts 2- Cutting Veg.
Mts 3- Heating Oil
Mts 3- Cutting Veg.
Mts 4- Heating Oil
Mts 4- Cutting Veg.
Mts 5- Cutting Veg.
Mts 5- Heating Oil
Mts 6- Cutting Veg.
Mts 6- Heating Oil
CUTTING VEG. IS OVER
HEATING OIL IS OVER
Main Program COOKING proceeds...
Click to Thread Creation using RUNNABLE interface
No comments:
Post a Comment