Multithreading:-: Smallest Unit of Processing
Multithreading:-: Smallest Unit of Processing
Multithreading in java is a process of executing multiple threads simultaneously. Thread is basically a lightweight sub-process, a
smallest unit of processing.
Although the main thread is created automatically when your program is started, it can be controlled through a Thread object. To do so, you
must obtain a reference to it by calling the method currentThread( ), which is a public static member of Thread. Its general form is shown here:
This method returns a reference to the thread in which it is called. Once you have a reference to the main thread, you can control it just like any
other thread.
Multithreading is a Java feature that allows concurrent execution of two or more parts of a program for maximum utilization of CPU. Each part
of such program is called a thread. So, threads are light-weight processes within a process.
We create a new class which implements java.lang.Runnable interface and override run() method. Then we instantiate a Thread object and call
start() method on this object.
After you create a class that implements Runnable, you will instantiate an object of type
Thread from within that class. Thread defines several constructors. The one that we will use
is shown here:
Thread(Runnable threadOb, String threadName)
In this constructor, threadOb is an instance of a class that implements the Runnable interface.
This defines where execution of the thread will begin. The name of the new thread is specified
by threadName.
After the new thread is created, it will not start running until you call its start( ) method,
which is declared within Thread. In essence, start( ) executes a call to run( ). The start( )
method is shown here:
Extending Thread
The second way to create a thread is to create a new class that extends Thread, and then to
create an instance of that class. The extending class must override the run( ) method, which
is the entry point for the new thread. It must also call start( ) to begin execution of the new
thread. Here is the preceding program rewritten to extend Thread: