Monday, 19 January 2015

What is Multitasking in Java

Multitasking:

Performing multiple task at the same time is know as Multitasking.

How to perform single task by multiple threads ?

If you have to perform single task by many threads, have only one run() method.
For example:
>1. Program of performing single task by multiple threads.

class Test extends Thread{
public void run(){
System.out.println("this is task one");
}
public static void main(String args[]){
Test t1=new Test();
Test t2=new Test();
Test t3=new Test();
t1.start();
t2.start();
t3.start();
}
}

Output: this is task one
        this is task one
        this is task one

       
>2. Program of performing single task by multiple threads.

class Test implements Runnable{
public void run(){
System.out.println("this is task one");
}
public static void main(String []args){
Thread t1 =new Thread(new Test());  //passing annonymous object of Test class
Thread t2 =new Thread(new Test());
t1.start();
t2.start();
 }
}   

Output: this is task one
        this is task one


Note: Each thread run in a separate callstack.   

How to perform multiple tasks by multiple threads (multtasking in multithreading) ?   

If you have to perform multiple tasks by multiple threads,you have to use multiple run() methods.
For example:
>1. Program of performing two tasks by two threads:

class Test1 extends Thread{
public void run(){
System.out.println("this is task one");
}
}
class Test2 extends Thread{
public void run(){
System.out.println("this is task two");
 }
}
class Test{
public static void main(String []args){
Test1 t1=new Test1();
Test2 t2=new Test2();
t1.start();
t2.start();
 }
}

Output: this is task one
        this is task two

       
Same example as above by annonymous class that extends Thread class:

>2. Program of performing two tasks by two threads

class Test{
public static void main(String []args){
Thread t1=new Thread(){
public void run(){
System.out.println("this is task one");
 }
};
Thread t2=new Thread(){
public void run(){
System.out.println("this is task two");
}
};
t1.start();
t2.start();
}
}

Output: this is task one
        this is task two


Same example as above by annonymous class that implements Runnable interface:       

>3. Program of performing two tasks by two threads

class Test{
public static void main(String []args){
Runnable r1=new Runnable(){
public void run(){
System.out.println("this is task one");
}
};
Runnable r2=new Runnable(){
public void run(){
System.out.println("this is task two");
}
};
Thread t1=new Thread(r1);
Thread t2=new Thread(r1);
t1.start();
t2.start();
}
}

Output: this is task one
       this is task two
      

      
Next---> What is Thread Schedular in Java
       
       
       

No comments:

Post a Comment