+1 vote
60 views

Why we use thread concept?
Give some eg...

please help me understand them with example

asked Jan 9, 2016 in Computer Science - IT by Dharani
edited Mar 16, 2016 by slow_learner | 60 views

2 Answers

+1 vote
Best answer

hi,

    i will explain some points about java threads..

What is thread??

  • Thread is a single process

Use of thread??

  • Executing multiple processes at the same time called multithreading or multiprocessing…
  • Thread is used to create animation in java..for simple example a small ball movement done by multithread is shown in the example :

 

Examples

       Multiprocessing :

  class loop1 extends Thread
{
     public void run()
     {
     for(int i=1;i<=2;i++)
                {
                     System.out.println("out");
                     try
                     {
                     Thread.sleep(1000);
                    }
                     catch(Exception e)
                     {
                 }
              }
     }
}

class loop2 extends Thread

{
     public void run()
     {
     for(int i=1;i<=2;i++)
                {
                     System.out.println("in");
                     try
                     {
                     Thread.sleep(1000);
                    }
                     catch(Exception e)
                     {
                 }
              }
     }
}

class multi
{
     public static void main(String args[]) throws InterruptedException
     {
           loop1 t1=new loop1();
           t1.start();  
           loop2 t2=new loop2();
          t2.start();
     }
}

 

Output:

out

in

out

in
  • See the output,  both for loops are running concurrently Is called multiprocessing..

 

 

Animation

 

import java.awt.*;
import java.applet.*;
public class animation extends Applet implements Runnable
{

Thread mythread;
int p=0;
       public void start()
{

mythread=new Thread(this);
mythread.start();

}

public  void run()

{

while(true)

{


for(p=0;p<=getSize().width;p+=200)

{

repaint();
try

{

mythread.sleep(300);

}

catch(InterruptedException e)

{}


} } }


public void paint(Graphics f)

{

f.setColor(Color.red);
f.fillOval(p,50,30,30);

}
}

 

Try the above example the small ball move from left to right direction.

  • Computer games are example for multithread..

Thank you

answered Jan 11, 2016 by gypsiii
edited Apr 6, 2016 by slow_learner
0 votes
Threading is a type of facility that allows multiple activities to work simultaneously within a single process.

Java is a multi threading programming language.So, thread is used to make the maximum use of the multiprocessor systems.The basic unit of scheduling is generally the thread; if a program has only one active thread, it can only run on one processor at a time. If a program have mutiple threads then it can schedule those multiple thread at once. It is also used to create animation in java.
answered Jan 12, 2016 by Shikha tyagi