Multi Threading in Java
Multi Threading in Java
BASICS
By Jeevesh Mishra
Multi Threading Concepts
• Overview of Thread
• Life Cycle of A Thread
• Thread Creation
• Thread Constructors
• Introduction to Multithreading
• Creation of Multiple Threads
• Thread Priorities and Scheduler
• Deadlock
• Lock and Synchronized Threads
• Inter-Thread Communication
• Daemon Thread
Overview of a Thread
• In Java Programming language, thread is a sequential path of code execution within
a program. Each thread has its own local variables, program counter and lifetime. In
single threaded runtime environment, operations are executes sequentially i.e. next
operation can execute only when the previous one is complete. It exists in a common
memory space and can share both data and code of a program. Threading concept is
very important in Java through which we can increase the speed of any application.
You can see diagram shown below in which a thread is executed along with its
several operations with in a single process.
Overview contd…
Main Thread (or main method)
When any standalone application is running, it
firstly execute the main() method runs in a one
thread, called the main thread. If no other
threads are created by the main thread, then
program terminates when the main() method
complete its execution. The main thread creates
some other threads called child threads. The
main() method execution can finish, but the
program will keep running until the all threads
have complete its execution.
Life Cycle of Threads
• When you are programming with threads, understanding the life cycle of thread is
very valuable. While a thread is alive, it is in one of several states. By invoking start()
method, it doesn’t mean that the thread has access to CPU and start executing
straight away. Several factors determine how it will proceed.
• In Java, an object of the Thread class can represent a thread. Thread can
be implemented through any one of two ways:
– Extending the java.lang.Thread Class
– Implementing the java.lang.Runnable Interface
Thread Creation
I. Extending the java.lang.Thread Class
For creating a thread a class have to extend the Thread Class. For creating a thread by this procedure you have
to follow these steps:
• Extend the java.lang.Thread Class.
• Override the run( ) method in the subclass from the Thread class to define the code executed by the thread.
• Create an instance of this subclass. This subclass may call a Thread class constructor by subclass constructor.
• Invoke the start( ) method on the instance of the class to make the thread eligible for running.
• The following program demonstrates a single thread creation extending the "Thread" Class:
• class MyThread extends Thread{ String s=null;
MyThread(String s1){
s=s1;
start();
}
public void run(){
System.out.println(s);
}
}
public class RunThread{
public static void main(String args[]){
MyThread m1=new MyThread("Thread started....");
}
}
Thread Creation
• Output of the Program is :
• C:\j2se6\thread>javac RunThread.java
C:\j2se6\thread>java RunThread
Thread started....
Thread creation
II. Implementing the java.lang.Runnable Interface
The procedure for creating threads by implementing the
Runnable Interface is as follows:
• A Class implements the Runnable Interface, override
the run() method to define the code executed by
thread. An object of this class is Runnable Object.
• Create an object of Thread Class by passing a
Runnable object as argument.
• Invoke the start( ) method on the instance of the
Thread class.
Thread creation
• The following program demonstrates the thread creation implenting
the Runnable interface:
• class MyThread1 implements Runnable{
Thread t;
String s=null; MyThread1(String s1){
s=s1;
t=new Thread(this);
t.start();
}
public void run(){
System.out.println(s);
}
}
public class RunableThread{
public static void main(String args[]){
MyThread1 m1=new MyThread1("Thread started....");
}
}
Thread creation
• However, this program returns the output
same as of the output generated through
the previous program.
• Output of the Program is:
• C:\j2se6\thread>javac
RunableThread.java
C:\j2se6\thread>java RunableThread
Thread started....
Thread Creation
There are two reasons for implementing a
Runnable interface preferable to extending the
Thread Class:
• If you extend the Thread Class, that means that
subclass cannot extend any other Class, but if
you implement Runnable interface then you can
do this.
• The class implementing the Runnable interface
can avoid the full overhead of Thread class
which can be excessive.
Thread Constructors
Then the newly formed group2 comes under group1. If you want a parent group
other than default then you have to specify the parent group at the time of creation.
• Introduction
So far you have learned about a single
thread. Lets us know about the concept of
multithreading and learn the
implementation of it. But before that, lets
be aware from the multitasking.
Multi Threading in Java contd..
• Multitasking :
As we have seen different states that may be occur with the single thread.
A running thread can enter to any non-runnable state, depending on the
circumstances. A thread cannot enters directly to the running state from
non-runnable state, firstly it goes to runnable state. Now lets understand
the some non-runnable states which may be occur handling the
multithreads.
Multithreading in Java contd…
Non-Runnable states understanding :
• Sleeping – On this state, the thread is still alive but it is not runnable, it might be return to
runnable state later, if a particular event occurs. On this state a thread sleeps for a specified
amount of time. You can use the method sleep( ) to stop the running state of a thread.
static void sleep(long millisecond) throws InterruptedException
• Waiting for Notification – A thread waits for notification from another thread. The thread sends
back to runnable state after sending notification from another thread.
final void wait(long timeout) throws InterruptedException
final void wait(long timeout, int nanos) throws InterruptedException
final void wait() throws InterruptedException
• Blocked on I/O – The thread waits for completion of blocking operation. A thread can enter on
this state because of waiting I/O resource. In that case the thread sends back to runnable state
after availability of resources.
• Blocked for joint completion – The thread can come on this state because of waiting the
completion of another thread.
• Blocked for lock acquisition – The thread can come on this state because of waiting to acquire
the lock of an object.
Creation of Multiple Threads
• class MyThread1 implements Runnable{
Thread t;
MyThread1(String s) {
t=new Thread(this,s);
t.start();
}
public void run() {
for(int i=0;i<5;i++) {
System.out.println("Thread Name :"+Thread.currentThread().getName());
try {
Thread.sleep(1000);
}catch(Exception e){}
}
}
}
public class RunnableThread1{
public static void main(String args[]) {
System.out.println("Thread Name :"+Thread.currentThread().getName());
MyThread1 m1=new MyThread1("My Thread 1");
MyThread1 m2=new MyThread1("My Thread 2");
}
}
Creation of multiple threads
• Output of the program:
Thread Priorities
• When a Java thread is created, it inherits its priority from the thread that created
it. At any given time, when multiple threads are ready to be executed, the
runtime system chooses the runnable thread with the highest priority for
execution. In Java runtime system, preemptive scheduling algorithm is
applied. If at the execution time a thread with a higher priority and all other
threads are runnable then the runtime system chooses the new higher priority
thread for execution. On the other hand, if two threads of the same priority are
waiting to be executed by the CPU then the round-robin algorithm is applied in
which the scheduler chooses one of them to run according to their round of
time-slice.
Thread Scheduler
• In the implementation of threading scheduler usually
applies one of the two following strategies:
• Preemptive scheduling – If the new thread has a
higher priority then current running thread leaves the
runnable state and higher priority thread enter to the
runnable state.
• Time-Sliced (Round-Robin) Scheduling – A running
thread is allowed to be execute for the fixed time, after
completion the time, current thread indicates to the
another thread to enter it in the runnable state.
Program for getting thread priorities
• You can also set a thread's priority at any time after its creation using the setPriority method. Lets see, how to set and get the priority of a thread.
•
• class MyThread1 extends Thread{
MyThread1(String s){
super(s);
start();
}
public void run(){
for(int i=0;i<3;i++){
Thread cur=Thread.currentThread();
cur.setPriority(Thread.MIN_PRIORITY);
int p=cur.getPriority();
System.out.println("Thread Name :"+Thread.currentThread().getName());
System.out.println("Thread Priority :"+cur);
}
}
}
class MyThread2 extends Thread{
MyThread2(String s){
super(s);
start();
}
public void run(){
for(int i=0;i<3;i++){
Thread cur=Thread.currentThread();
cur.setPriority(Thread.MAX_PRIORITY);
int p=cur.getPriority();
System.out.println("Thread Name :"+Thread.currentThread().getName());
System.out.println("Thread Priority :"+cur);
}
}
}
public class ThreadPriority{
public static void main(String args[]){
MyThread1 m1=new MyThread1("My Thread 1");
MyThread2 m2=new MyThread2("My Thread 2");
}
}
Output of the Program:
• javac ThreadPriority.java
C:\jeevesh>java ThreadPriority
Thread Name :My Thread 1
Thread Name :My Thread 2
Thread Priority :Thread[My Thread 2,10,main]
Thread Name :My Thread 2
Thread Priority :Thread[My Thread 2,10,main]
Thread Name :My Thread 2
Thread Priority :Thread[My Thread 2,10,main]
Thread Priority :Thread[My Thread 1,1,main]
Thread Name :My Thread 1
Thread Priority :Thread[My Thread 1,1,main]
Thread Name :My Thread 1
Thread Priority :Thread[My Thread 1,1,main]
• In this program two threads are created. We have set up maximum priority for the first
thread "MyThread2" and minimum priority for the first thread "MyThread1" i.e. the
after executing the program, the first thread is executed only once and the second
thread "MyThread2" started to run until either it gets end or another thread of the
equal priority gets ready to run state.
Deadlock
// statements to be synchronized
}
Synchronization contd …
Lock:
• Lock term refers to the access granted to a particular thread that
can access the shared resources. At any given time, only one
thread can hold the lock and thereby have access to the shared
resource. Every object in Java has build-in lock that only comes in
action when the object has synchronized method code. By
associating a shared resource with a Java object and its lock, the
object can act as a guard, ensuring synchronized access to the
resource. Only one thread at a time can access the shared resource
guarded by the object lock.
• Since there is one lock per object, if one thread has acquired the
lock, no other thread can acquire the lock until the lock is not
released by first thread. Acquire the lock means the thread currently
in synchronized method and released the lock means exits the
synchronized method.
Synchronization And Lock
• Remember the following points related to lock and synchronization:
• Only methods (or blocks) can be synchronized, Classes and variable cannot be synchronized.
• Each object has just one lock.
• All methods in a class need not to be synchronized. A class can have both synchronized and non-synchronized
methods.
• If two threads wants to execute a synchronized method in a class, and both threads are using the same instance
of the class to invoke the method then only one thread can execute the method at a time.
• If a class has both synchronized and non-synchronized methods, multiple threads can still access the class's non-
synchronized methods. If you have methods that don't access the data you're trying to protect, then you don't
need to synchronize them. Synchronization can cause a hit in some cases (or even deadlock if used incorrectly),
so you should be careful not to overuse it.
• If a thread goes to sleep, it holds any locks it has—it doesn't release them.
• A thread can acquire more than one lock. For example, a thread can enter a synchronized method, thus acquiring
a lock, and then immediately invoke a synchronized method on a different object, thus acquiring that lock as well.
As the stack unwinds, locks are released again.
• You can synchronize a block of code rather than a method.
• Constructors cannot be synchronized
Synchronization and Lock
• There are two ways to synchronized the execution of code:
• Synchronized Methods
• Synchronized Blocks (Statements)
• Synchronized Methods:
• Any method is specified with the keyword synchronized is only executed
by one thread at a time. If any thread want to execute the synchronized
method, firstly it has to obtain the objects lock. If the lock is already held by
another thread, then calling thread has to wait.
Synchronized methods are useful in those situations where methods are
executed concurrently, so that these can be intercommunicate manipulate
the state of an object in ways that can corrupt the state if . Stack
implementations usually define the two operations push and pop of
elements as synchronized, that’s why pushing and popping are mutually
exclusive operations. For Example if several threads were sharing a stack, if
one thread is popping the element on the stack then another thread would
not be able to pushing the element on the stack.
Synchronization Program
• The following program demonstrates the synchronized method:
•
• class Share extends Thread{
static String msg[]={"This", "is", "a", "synchronized", "variable"};
Share(String threadname){
super(threadname);
}
public void run(){
display(getName());
}
public synchronized void display(String threadN){
for(int i=0;i<=4;i++)
System.out.println(threadN+msg[i]);
try{
this.sleep(1000);
}catch(Exception e){}
}
}
public class SynThread1 {
public static void main(String[] args) {
Share t1=new Share("Thread One: ");
t1.start();
Share t2=new Share("Thread Two: ");
t2.start();
}
} Output of the program is:
• C:\nisha>javac SynThread.java
C:\nisha>java SynThread
Thread One: This
Thread One: is
Thread One: a
Thread One: synchronized
Thread One: variable
Thread Two: This
Thread Two: is
Thread two: a
Thread Two: synchronized
Thread Two: variable
Synchronization Program
• In this program, the method "display( )" is
synchronized that will be shared by both
thread's objects at the time of program
execution. Thus only one thread can
access that method and process it until all
statements of the method are executed.
Synchronization implementation
• Synchronized Blocks (Statements)
• Another way of handling synchronization is
Synchronized Blocks (Statements). Synchronized
statements must specify the object that provides the
native lock. The synchronized block allows execution of
arbitrary code to be synchronized on the lock of an
arbitrary object.
• General form of synchronized block is:
• synchronized (object reference expression)
{
// statements to be synchronized
}
• The following program demonstrates the synchronized block that shows the same output as the output of the
previous example:
•
• class Share extends Thread{
static String msg[]={"This", "is", "a", "synchronized", "variable"};
Share(String threadname){
super(threadname);
}
public void run(){
display(getName());
}
public void display(String threadN){
synchronized(this){
for(int i=0;i<=4;i++)
System.out.println(threadN+msg[i]);
try{
this.sleep(1000);
}catch(Exception e){}
}
}
public class SynStatement {
public static void main(String[] args) {
Share t1=new Share("Thread One: ");
t1.start();
Share t2=new Share("Thread Two: ");
t2.start();
}
} Output of the Program
• C:\nisha>javac SynStatement.java C:\nisha>java SynStatement
Thread One: This
Thread One: is
Thread One: a
Thread One: synchronized
Thread One: variable
Thread Two: This
Thread Two: is
Thread Two: a
Thread Two: synchronized
Thread Two: variable
Inter-Thread Communication
• public class DemoWait extends Thread{
int val=20;
public static void main(String args[]) {
DemoWait d=new DemoWait();
d.start();
new Demo1(d);
}
public void run(){
try {
synchronized(this){
wait();
System.out.println("value is :"+val);
}
}catch(Exception e){}
}
public void valchange(int val){
this.val=val;
try {
synchronized(this) {
notifyAll();
}
}catch(Exception e){}
}
}
Inter-Thread Communication
• class Demo1 extends Thread{
DemoWait d;
Demo1(DemoWait d) {
this.d=d;
start();
}
public void run(){
try{
System.out.println("Demo1 value is"+d.val);
d.valchange(40);
}catch(Exception e){}
}
}
Inter-Thread Communication
• Output of the program is:
• C:\jeevesh\thread>javac DemoWait.java
C:\jeevesh\thread>java DemoWait
Demo1 value is20
value is :40
C:\jeevesh\thread>
Daemon Threads