Core Java - [Multithreading Fundamentals]

♠ Posted by Unknown in at 01:41

Multithreaded Programming in Java


Multithreading is a conceptual programming paradigm where a program (process) is divided into two or more subprograms (processes), which can be implemented at the same time in parallel. For example, one subprogram can display an animation on the screen while another may build the next animation to be displayed. This is something similar to dividing a task into subtasks and assigning them to different people for execution independently and simultaneously.

A thread is similar to a program that has a single flow of control. It has a beginning, a body, and an end, and executes commands sequentially. In fact all main programs can be called single-threaded programs.

The main thread is actually the main method module, which is designed to create and start the other three threads, namely A, B, and C.

Once initiated by the main thread, the threads A, B, and C run concurrently and share the resources jointly. The ability of a language to support multithreads is referred to as concurrency. Since threads in Java are subprograms of a main applications program and share the same memory space, they are known as lightweight threads or lightweight processes.

Threads are extensively used in Java-Enabled browsers such as HotJava. These browsers can download a file to the local computer, display a Web Page in the window, output another Web page to a printer and so on.

CREATING THREADS :

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

                        public void run()
                        {
                                    …………
                                    ……….. (statements for implementing thread)
                                    ………..
                        }

The run() method should be invoked by an object of the concerned thread. This can be achieved by creating the thread and initiating 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, run (), that is to be defined in the method with the code to be executed by the thread.

0 comments:

Post a Comment