Multi-threading: – Multi threading is a conceptual programming paradigm where a program or process is divided into two or more sub programs or process, which can be implemented at the same time in parallel. For example, one sub program can display an animation on the screen while another may have built the next animation to be display. This is something similar to dividing a task into sub task and assigning then to different people for execution indecently and simultaneously. Java programs contain only a single sequential flow of control. Multi-threading is a unique property of java application. That is, java enables us to use multiple flows of control in developing programs. Each flow of control may be thought of as a separate tiny program known as a thread that runs in parallel to others.

Multi-threading is a powerful programming tools that makes java distinctly different from its programming language. Multi-threading is useful in a number of ways. It enables programmers to do multiple thing at one time. They can divide a long program into thread and execute them parallel.

Creating threads: – Creating threads in java is simple. Threads are implemented in the form of objects that content a method called run(). The run() method is the heart and soul of any thread. It makes up the entire body of a thread and is only method in which the thread’s behavior can be implemented. Syntax of the run method is –

public void run()
{
                Statements of thread
}

The run() method should be invoked by an object of the concerned thread. This can be achieved by creating the thread and initializing it with the help of another thread method called start(). A new thread can be created in two ways –

  1. By creating a thread class: – Define a class that extends thread class and override its run() method with the code required by the thread.
  2. By converting a class to a thread: – Define a class that implements runnable interface. The runnable interface has only one method called run() that is to be defined in the method with the code to be executed by the thread.

The approach to be used depends on what the class we are creating requires. If it requires to extend another class, then we have no choice but to implement the runnable interface, since java classes cannot have to supper classes.

Advertisements