The ability of the Operating system to execute several programs simultaneously is known as multitasking. In system terminology, it is is a powerful programming tool that makes it possible to achieve concurrent execution of multiple units of a program called multithreading. In multithreading, the application (process) is divided into two or more subprograms (processes), Several such processes originating from a single task, can be simultaneously started and handled by Java, which can be implemented at the same time in parallel. The processor is doing only one thing at a time, but it switches between the processes so fast that it appears to human beings that all of them are being done simultaneously. This mechanism of treating a single task as several independent processes simultaneously is called multithreading. Each separate process is called a thread. Each thread is executed one at a time in the CPU. Multithreading enables a program to do more than one task at a time and also to synchronize these tasks.
A thread is similar to a program that has a single flow of control. The programs so far we have seen are called single-threaded programs, i.e., it has a beginning, a body, and an end. Java builds thread support directly into the language. Multithreading support for Java includes thread creation, thread prioritizing, thread scheduling, resource locking (thread synchronization) and establishing inter-thread communication.
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 (or module) known as the thread that runs in parallel to others. A program that contains multiple flows of control is known as a multithreaded program.
The ability of language to support multithread is referred to as concurrency. Since threads in Java are subprograms of the main application and share the same memory space, they are also known as lightweight threads or lightweight processes.
In multithreading, the same set of variables and memory space is shared by the threads. When a thread was dealing with a sub-task, say reading an input stream, has to wait for the arrival of a byte, such a thread exit the CPU and another thread, say drawing a graphic on a screen, may enter the CPU and continue its task. Thus Java’s thread provides a mechanism to utilize the CPU time more optimally. Multithreading finds use in a variety of applications. The threading mechanism is supported by Java’s Thread class contained in java.lang package.
We’ll be covering the following topics in this tutorial:
Advantages of Multithreading
1. It enables the programmers to do multiple things at a time.
2. They can divide a long program (containing operations that are conceptually concurrent) into threads and execute them in parallel.
3. 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.
What is Thread?
A thread is a single sequential flow of control within a program. It differs from a process in that a process is a program executing in its own address space whereas a thread is a single stream of execution within a process.
A thread can be defined as a process in execution within a program. A thread by itself is not a complete program and cannot run on its own. It runs within a program; however each thread has a beginning, and an end, and a sequential flow of execution at a single point of time. At any given instant within the run-time of the program, only one thread will be executed by the processor.
Multithreading allows a program to be structured as a set of individual units of control that run in parallel; however, the Central Processing Unit (CPU) can only run one process at a time. The CPU time is divided into slices and a single thread will run in a given time slice. Typically, the CPU switches between multiple threads and runs so fast that it appears as if all threads are running at the same time. It is better, as a programming practice, to identify different parts of the program that can perform in parallel and implement them into independent threads.
Multithreading differs from multitasking: multitasking allows multiple tasks (which can be processes or programs) to run concurrently whereas multithreading allows multiple units within a program (threads) to run concurrently.
Unlike the processes in some operating systems (for example, Unix), the threads in Java are ‘light-weight processes’ as they have relatively low overheads and share common memory space. This facilitates an effective and inexpensive communication between threads.
Thread Creation
When a Java program begins execution, it always has atleast one thread, i.e., the main thread. In regular Java application program, this thread starts at the beginning of main () method that means that when your program creates a thread, it is in addition to the main thread of execution that created it. Java provides two ways to make your class behave like a thread.
• By extending a java .lang. Thread class and override its run () method
• By implementing the Runnable interface and implementing its run() method
Now the question arises which of the two thread creating techniques one should use. The first technique can only be used for classes that do not already extend any other class. Therefore, we stick with the second approach which is always applicable.
Before creating a class that extends the Thread class, you need to understand the java.lang.Thread class. The Thread class lets you create an object that can be run as a thread in a multithreaded Java application. It is a direct subclass of the object class, and it implements the Runnable interface. A Thread object controls a thread running under the JVM. The Thread class contains the following constructors for creating threads and methods for controlling threads.
Constructors | Purpose |
Thread () | Creates an instance of the Thread class. |
Thread(String name) | Creates a Thread object and assigns a specified name to the thread. |
Thread(Runnable target) | Creates a new Thread object that uses the run () method of the specified target. |
Method | Purpose |
static Thread currentThread () | Returns the reference of the currently executing Thread object. |
void final start() | Causes the associated thread to start execution. The JVM calls the run () method of this thread. |
void run () | If the thread was created using separate Runnable object then that Runnable object’s run ()method is called, otherwise this method does nothing and returns. |
String getName() void setName(String name) | Returns the name of the thread. Changes the name of the thread to the one specified in the |
static void sleep (long millseconds) | Cause the currently executing thread to sleep for the specified number of milliseconds. This method throws InterruptedException exception and must be used within the try catch block. |
static void yield() | Causes the currently running thread to temporarily pause and allow other threads to execute. |
final void setPriority (int newPriority) | Changes the priority of the thread with the value specified in the argument. |
int getpriority() | Returns threads priority. |
final boolean isAlive() | Tests if the thread is alive. |
Method | Purpose |
void setDaemon (boolean on) | Marks the thread as either a user thread or a daemon thread. |
boolean isDaemon() | Tests whether a thread is Daemon thread or not. |
final void join() | Waits for the thread to die. |
void interrupt() | Interrupts a thread. |
void stops () | Stops the thread. |
Example of Thread
class NewThreadDemo implements Runnable {
Thread t;
NewThreadDemo(String threadName){
t = new Thread(this, threadName);
System.out.println(“New userdefined child thread created”+threadName);
t.start();
}
public void run(){
try{
for(int i =1; i <=10; i++){
System.out.println(“Child Thread: [“+Thread.currentThread().getName()+“] “+ i);
Thread.sleep(500);
}
}
catch(InterruptedException e){
System.out.println(“UseDefine Child interrupted.”);
}
System.out.println(“Exiting UserDeinfed child thread.”);
}
}
class MultiThreadDemo {
public static void main(String args[]){
new NewThreadDemo(“Child_One”);
new NewThreadDemo(“Child_Two”);
new NewThreadDemo(“Child_Three”);
new NewThreadDemo(“Child_Four”);
try{
for(int i =1; i <10; i++){
System.out.println(“Main Thread: “+ i);
Thread.sleep(500);
}
}
catch(InterruptedException e){
System.out.println(“Main thread interrupted.”);
}
System.out.println(“Main thread exiting.”);
}
}
Output