You are on page 1of 25

Multithreading in Java

Introducing Multithreading in Java

What Is a Thread? A thread in a Java program is the smallest unit of executable code.

Introducing Multithreading in Java

A multithreaded program contains two or more parts that can run concurrently. Each part of such a program is called a thread. Multithreading enables to write a very efficient programs that make maximum use of the CPU. Multithreading allows to use the idle time like user input and put it to good use.

Introducing Multithreading in Java

A thread is similar to a real process in that a thread and a running program are both a single sequential flow of control. A thread is considered lightweight because it runs within the context of a full-blown program. Each threads in a program runs independently from the others, but at the same time.

The Life Cycle of a Thread

Threads exists in several states. Ready Running Suspended Resumed Blocked A thread can be running. It can be ready to run as soon as it gets CPU time.

The Life Cycle of a Thread

A running method can be suspended, which temporarily suspend the activities. A suspended thread can be then resumed. A thread can be blocked when waiting for a resource. At any time the thread can be terminated.

The Life Cycle of a Thread

A terminated thread cannot be resumed. A thread can voluntarily relinquish control by explicitly yielding, sleeping or blocking. A thread can be preempted by the higher priority thread.

Understanding Thread Priority

Thread priorities are integers that specify the relative priority of one another. Thread priorities are used by the thread scheduler to decide when each thread should be allowed to run. When a Java thread is created, it inherits its priority from the thread that created it. You can also modify a thread's priority at any time after its creation using the setPriority method. final void setPriority(int level)

Understanding Thread Priority

The level specifies the new priority for the calling string. The value level must be between the range MIN_PRIORITY and MAX_PRIPRITY. The values are ranging from 0 to 10 respectively. The default priority is NORM_PRIORITY, which is 5. To obtain the current priority of a thread, use getPriority() method. final int getPriority()

Main Thread
When java program starts it usually called the main thread of the program. All other threads are spawned from the main thread. The main thread must be the last thread to finish execution. When the main thread stops, the program terminates.


Creating a Thread
There are two ways to create a thread. 1. By implementing the Runnable interface. 2. By extending the Thread class.


Using Runnable interface

The easiest way to create a thread is to create a class that implements the Runnable interface and implement the method called run() public void run() Inside run() method, define the code that constitutes the new thread. The run() method can call other methods. The thread will end when run() returns.

Creating a Thread
public class RunnableDemo implements Runnable { Thread t; public RunnableDemo() { t=new Thread(this,Runnale Demo); t.start(); } public void run() { // thread code } } The Thread Constructor Thread(Runnable threadObj, String threadName) Example:


Using Thread class

Create a new class that extends Thread class and then create an instance for that class. The extending class must override the run() method. It must also call the start() method to begin execution of the new thread.

is responsible for two things: Instructing the JVM to create a new thread Call your Thread objects run() method in the new thread


Creating a Thread
public class ThreadDemo extends Thread { public ThreadDemo() { super(demo thread); start(); } public void run() { // thread code } }

The super() used inside the ThreadDemo class take the form of Thread constructor public Thread (String threadName) Example:

Creating Multiple Thread

Multiple threads run concurrently on the system Multiple tasks can be handled at once. Processing can be done in the background so as not to interrupt the user. Java allows to spawn as many threads as it needs. Example:

Thread methods
void start() Causes this thread to begin execution; the Java Virtual Machine calls the run method of this thread. static void sleep(long millis) Causes the currently executing thread to sleep (temporarily cease execution) for the specified number of milliseconds. static void sleep(long millis, int nanos) Causes the currently executing thread to sleep (cease execution) for the specified number of milliseconds plus the specified number of nanoseconds.

Thread methods
public final void setName(String name) Changes the name of this thread to be equal to the argument name. public final String getName() Returns this thread's name. public final ThreadGroup getThreadGroup() Returns the thread group to which this thread belongs. This method returns null if this thread has died (been stopped).

Thread methods
public static int activeCount() Returns the number of active threads in the current thread's thread group. public String toString() Returns a string representation of this thread, including the thread's name, priority, and thread group. public static Thread currentThread() Returns a reference to the currently executing thread object.


Thread methods
public void destroy() Destroys this thread, without any cleanup public final boolean isAlive() Tests if this thread is alive. A thread is alive if it has been started and has not yet died. public final void join(long millis) throws InterruptedException Waits at most millis milliseconds for this thread to die. A timeout of 0 means to wait forever.

When two or more threads needs to access the shared resources, that resource will be used by only one thread at a time. The process by which this is achieved is called synchronization. Java uses the concept called monitor to achieve synchronization. Monitor is a object that is used as a mutually exclusive lock.


Only one thread can enter a monitor at a time. All other threads attempting to enter in to the monitor will be suspended until the first thread exits the monitor.


Java allows to use a keyword called synchronized. class SyncDemo { synchronized void mathod() { // method body } } Example:


Interthread communication
Java provides the interthread communication via the wait(), notify() and notifyAll() methods. All the three methods can be called only from within a synchronized method Void wait(long timeout) Causes current thread to wait until either another thread invokes the notify() method or the notifyAll() method for this object, or a specified amount of time has elapsed.


Interthread communication
Void wait() Causes current thread to wait until another thread invokes the notify() method or the notifyAll() method for this object. void notify() Wakes up a single thread that is waiting on this object's monitor. void notifyAll() Wakes up all threads that are waiting on this object's monitor.