how to implement Multiple threads or process with threads

how to implement Multiple threads or process with threads | Javamazon:


Multiple threads or process with threads

In Order to better understand about the Threads and Process please refer Oracle Doc , please do not completely rely on StackOverflow or other similar QA sites as these are collaboratively edited question and answer site and most of the professional and programmers who consider them self as Java GURUS end up either editing the Actual Meaning of Threads and Process according to their understanding and manipulating right answers of real programmers. If you go around Stackoverflow with Search keywords ‘Threads and Process” one could come to know there are about 10 different versions discussed considering last 200 such posts.So please do not refer such QA sites if you are a newbie but do refer Oracle Doc
The answer below is formed precisely referring to Standard Sun Oracle Notes:
In concurrent programming, there are two basic units of execution: processes and threads.
Process-and-Thread-relationship
______________________________________________________________________________________________
Processes:
A process has a self-contained execution environment. A process generally has a complete, private set of basic run-time resources; in particular, each process has its own memory space.
Threads
Threads are sometimes called lightweight processes. Both processes and threads provide an execution environment, but creating a new thread requires fewer resources than creating a new process.
______________________________________________________________________________________________
Each thread is associated with an instance of the class Thread. Threads exist within a process — every process has at least one. Threads share the process’s resources, including memory and open files. This makes for efficient, but potentially problematic, communication.Multithreaded execution is an essential feature of the Java platform. Every application has at least one thread — or several, if you count “system” threads that do things like memory management and signal handling. But from the application programmer’s point of view, you start with just one thread, called the main thread/Daemon Thread. This thread has the ability to create additional threads.
______________________________________________________________________________________________
An application that creates an instance of Thread must provide the code that will run in that thread. There are two ways to do this:
Provide a Runnable object. The Runnable interface defines a single method, run, meant to contain the code executed in the thread. The Runnable object is passed to the Thread constructor, as in the HelloRunnable example:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public class HelloRunnable implements Runnable {
 
public void run() {
 
System.out.println("Hello from a thread!");
 
}
 
public static void main(String args[]) {
 
(new Thread(new HelloRunnable())).start();
 
}
 
}
Subclass Thread. The Thread class itself implements Runnable, though its run method does nothing. An application can subclass Thread, providing its own implementation of run, as in the HelloThread example:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public class HelloThread extends Thread {
 
public void run() {
 
System.out.println("Hello from a thread!");
 
}
 
public static void main(String args[]) {
 
(new HelloThread()).start();
 
}
 
}
Both examples invoke Thread.start in order to start the new thread.
______________________________________________________________________________________________

Example to show how to implement thread by extending thread Class

thread can be created in Java programs in two ways – by extending Thread class and by implementing Runnableinterface. In case, where the class extends a Tread class, it must override run() method of the Thread class. The program may override the other methods also. If the program uses Runnable interface, it needs to implement only run() method.
The first way to create a thread is to create a subclass of the Thread class. This class must override the run( ) methodand it may also override the other methods defined with the class. Then the class that needs the thread can create an object of the class that extends thread class. Following example shows the concept of threads clearly.
class MyThread extends Thread
{
    MyThread ( )
    {
        .....
        .....
    }        

public void run ( ) //must override this method   

    {
        .....
        .....
    }    

        .....
}

public class MainClass
{    

  public static void main()     

{        

  MyThread t = new MyThread ();
   .......
   t.start () ;
   .......
   }
}
Let us now create a sample Fibonacci Program using threads that generates Fibonacci series. This program creates the thread by extending thread class:
class PrintFibo
{
    public static void main(String args[])
  {
    JavaFib t = new JavaFib (20);
    t.start ( );
  }
}

class JavaFib extends Thread
{
          //number of elements to generate in a series
            private int num;

            JavaFib (int itr)
              {
                num=itr;
              }       

            public void run()
            {
                long[] series = new long[num];

            //create first 2 series elements
               series[0] = 0;
               series[1] = 1;

            //create the Fibonacci series and store it in an array
                for(int i=2; i < num; i++)
                {
                  series[i] = series[i-1] + series[i-2];
                }

               //print the Fibonacci series numbers

               System.out.println("Fibonacci Series upto " + num);
               for(int i=0; i< num; i++)
               {
                System.out.print(series[i] + " ");
               }
            }
}
OUTPUT
Output of the Fibonacci Series Java Example would be

Fibonacci Series upto 20

0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181
To crate threads, create a new class that extends the Thread class, and instantiate that class. The extending class must override the run() method and call start() method to begin execution of the thread.
______________________________________________________________________________________________

Example to show how to implement Thread Class-Runnable Interface

Let us now create a sample Fibonacci Program using threads that generates Fibonacci series. This program creates the thread by extending thread class:

class PrintFibo
{
    public static void main(String args[])
  {
    JavaFib t = new JavaFib (20);
    t.start ( );
  }
}

class JavaFib extends Thread
{
   //number of elements to generate in a series
    private int num;

    JavaFib (int itr)
     {
       num=itr;
     }
    public void run()
     {
        long[] series = new long[num];
//create first 2 series elements
        series[0] = 0;
        series[1] = 1;

//create the Fibonacci series and store it in an array
    for(int i=2; i < num; i++)
        {
          series[i] = series[i-1] + series[i-2];
        }
//print the Fibonacci series numbers
     System.out.println("Fibonacci Series upto " + num);
        for(int i=0; i< num; i++)
          {
            System.out.print(series[i] + " ");
          }
        }
}
OUTPUT
Output of the Fibonacci Series Java Example would be

Fibonacci Series upto 20

0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181
To crate threads, create a new class that extends the Thread class, and instantiate that class. The extending class must override the run() method and call start() method to begin execution of the thread.
1)If you want to extend the Thread class then it will make your class unable to extend other classes as java is having single inheritance feature whereas If you implement runnable interface, you can gain better object-oriented design and consistency and also avoid the single inheritance problems.
2)Extending the thread will give you simple code structure in comparison to Runnable Interface.
3)Using Runnable Interface, you can run the class several times whereas Thread have the start() method that can be called only once
If you have had created a thread class by extending Thread class, you could have directly called start() method ast.start (), where t is a thread object. This is because thread class created by extending Thread class is a subclass of  Thread class, so it has all functionalities of a thread. While creating a thread implementing Runnable, a Thread object will have to be explicitly created which is what PrintFibo class is doing. It then passes JavaFib object as a parameter to this thread and runs it. This causes the run ( ) method of JavaFib class to get executed.
Now will rewrite the code by implementing Runnable Interface :
class PrintFibo
{
    public static void main(String args[])
  {
    JavaFib t = new JavaFib (20);
    t.start ( );
  }
}

class JavaFib extends Thread
{
   //number of elements to generate in a series
    private int num;

    JavaFib (int itr)
     {
       num=itr;
     }
    public void run()
     {
        long[] series = new long[num];
//create first 2 series elements
        series[0] = 0;
        series[1] = 1;

//create the Fibonacci series and store it in an array
    for(int i=2; i < num; i++)
        {
          series[i] = series[i-1] + series[i-2];
        }
//print the Fibonacci series numbers
     System.out.println("Fibonacci Series upto " + num);
        for(int i=0; i< num; i++)
          {
            System.out.print(series[i] + " ");
          }
        }
}
In general, I would recommend using something like Runnable rather than Threadbecause it allows you to keep your work only loosely coupled with your choice of concurrency. For example, if you use a Runnable and decide later on that this doesn’t in fact require it’s own Thread, you can just call threadA.run().
Runnable because:
  • •Leaves more flexibility for the Runnable implementation to extend another class
  • •Separates the code from execution
  • •Allows you to run your runnable from a Thread Pool, the event thread, or in any other way in the future.
  • Even if you don’t need any of this now, you may in the future. Since there is no benefit to overriding Thread,Runnable is a better solution.

0 comments:

Post a Comment