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: Program of performing single task by multiple threads
  1. class TestMultitasking1 extends Thread{  
  2.  public void run(){  
  3.    System.out.println("task one");  
  4.  }  
  5.  public static void main(String args[]){  
  6.   TestMultitasking1 t1=new TestMultitasking1();  
  7.   TestMultitasking1 t2=new TestMultitasking1();  
  8.   TestMultitasking1 t3=new TestMultitasking1();  
  9.   
  10.   t1.start();  
  11.   t2.start();  
  12.   t3.start();  
  13.  }  
  14. }  

Output:task one
       task one
       task one
Program of performing single task by multiple threads
  1. class TestMultitasking2 implements Runnable{  
  2. public void run(){  
  3. System.out.println("task one");  
  4. }  
  5.   
  6. public static void main(String args[]){  
  7. Thread t1 =new Thread(new TestMultitasking2());//passing annonymous object of TestMultitasking2 class  
  8. Thread t2 =new Thread(new TestMultitasking2());  
  9.   
  10. t1.start();  
  11. t2.start();  
  12.   
  13.  }  
  14. }  

Output:task one
       task one

Note: Each thread run in a separate callstack.

MultipleThreadsStack

No comments:

Post a Comment