Multi Threading (Autosaved)
Multi Threading (Autosaved)
Topics to Cover
• Introduction
• How to define a thread
• By extending Thread class
• By implementing Runnable Interface
• Getting and Setting Name of Thread
• Thread Priorities
• Method to Prevent Thread Execution
• Yield()
• Join()
• Sleep()
• Daemon Thread
Introduction
• Multi Programming: running multiple program on a single machine is
known as multi-programming
• It is divided into
• Multi-User
• Multi-tasking
Multi-Tasking
• Executing several tasks simultaneously is the concept of multitasking.
There are two types of multitasking’s.
• Process based multitasking.
• Thread based multitasking.
Process based Multi-tasking
• Executing several tasks simultaneously where each task is a separate
independent process such type of multitasking is called process based
multitasking.
• Example:
• While typing a java program in the editor we can able to listen mp3 audio
songs at the same time we can download a file from the net all these tasks
are independent of each other and executing simultaneously and hence it is
Process based multitasking.
Thread based Multi-Tasking
• Executing several tasks simultaneously where each task is a separate independent part of the
same program, is called Thread based multitasking. And each independent part is called a
"Thread".
• A thread is a light-weight smallest part of a process that can run concurrently with the other
parts(other threads) of the same process.
• This type of multitasking is best suitable for "programatic level".
• When compared with "C++", developing multithreading examples is very easy in java
because java provides in built support for multithreading through a rich API (Thread,
Runnable, ThreadGroup, ThreadLocal...etc).
• In multithreading on 10% of the work the programmer is required to do and 90% of the work
will be down by java API.
• The main important application areas of multithreading are:
• To implement multimedia graphics.
• To develop animations.
• To develop video games etc.
• To develop web and application servers
• Whether it is process based or Thread based the main objective of multitasking is to improve
performance of the system by reducing response time.
Defining a Thread
• We can define a Thread in the following 2 ways.
• By extending Thread class.
• By implementing Runnable interface.
Control flow of a Program
Class Test
{
static void display()
{
SOP(“hello”);
}
public static void main(String [] args)
{
display();
SOP(“hello”);
}
}
Here we have only one control flow that will move.
Another Example
Class Test int i=1;
{ while(true)
static void display() {
SOP(“hello”);
{ i++;
int i=1; }
while(true) }
{ }
SOP(“hello”); Output:
i++; The flow of control will stuck in display()
}
}
Target is to make display() as separate entity
public static void main(String [] args) that will run by its own. And main() should also
{ work as separate entity
display();
To achieve multi-threading in Java
• Thread class : when we have our own class and we want to achieve
multi-threading then we can write class_name extends thread
• Runnable Interface: when our class is already extending some class
and we want to achieve multi-threading then we can use Runnable
interface.
Example Thread
• Whenever you extend thread class and want to achieve
multithreading then you must override run() method which is of
public and void type. The logic of that program must be in run()
method.
• It can be considered as starting point of program same as main()
method.
• You also have to create object of thread class and use start() method
to start the thread.
Example Thread
class MyThread extends Thread int i=1;
{ while(true)
{
public void run()
System.out.println(i+"Hello");
{ i++;
int i=1; }
Defining a thread }
while(true)
}
{
System.out.println(i+"Hello");
i++;
} Job performed by thread
}
}
public class Test {
public static void main(String[] args) throws Exception{
// TODO code application logic hereThread Instantiation
MyThread t=new MyThread();
Start of Thread
t.start();
Another Way
int i=1;
public class Test extends Thread{ while(true)
public void run() {
System.out.println(i+"World");
{
i++;
int i=1; }
while(true) }
{ }
System.out.println(i+"Hello");
i++;
}
}
public static void main(String[] args) throws Exception{
// TODO code application logic here
Test t=new Test();
t.start();
Thread Scheduler
• Thread Scheduler is part of JVM, responsible to schedule thread
execution. If multiple threads are there then in which order thread
will execute is decided by thread scheduler. The order will be decided
based on algorithm that a scheduler is following, round robin or SJF
are few example. The algorithm varies from JVM to JVM.
Method start()
• Thread class start method is responsible
• to register the thread with thread scheduler
• To perform other necessary action
• Invoke run() method
Overloading run() method
• We can overload run() method but thread class start method will
always call no argument run() method. The other overloaded method
we have to call explicitly like normal method call.
Another Example
import java.util.*;
class MyThread extends Thread{
public void run() {
System.out.println(“no argument");
}
public void run(int x) {
System.out.println(“with argument");
}
}
public class Main{
public static void main(String[] args) {
MyThread my=new MyThread();
th.start();
}
}
What if run() is not overridden in class
import java.util.*;
class MyThread extends Thread{
}
public class Main{
public static void main(String[] args) {
MyThread my=new MyThread();
th.start();
}
}
If run method is not overrided then after start() method the Thread class run() method will be called.
The Thread class run() method is empty implementation. So the program will executed but we will not
get any output.
Overriding start() method
import java.util.*;
class MyThread extends Thread{
public void start() {
System.out.println(“start method");
}
public void run() {
System.out.println(“run method");
}
}
public class Main{
public static void main(String[] args) {
MyThread my=new MyThread();
th.start();
System.out.println(“main method");
}
}
In the above example we are caaling start() method from main() explicitly then thread class start() method will not be invoked and a separate thread
will not be created. So run() method will not be executed. Output will be start method followed by main method. The result is started by main()
method only, no separate thread will be created
Overriding start() method
import java.util.*;
class MyThread extends Thread{
public void start() {
super.start();
System.out.println(“start method");
}
public void run() {
System.out.println(“run method");
}
}
public class Main{
public static void main(String[] args) {
MyThread my=new MyThread();
th.start();
System.out.println(“main method");
}
}
Now two separate thread will be created main thread and child thread and result may vary between start() method followed by main
Overriding start() method
import java.util.*;
class MyThread extends Thread{
public void start() {
super.start();
System.out.println(“start method");
}
public void run() {
System.out.println(“run method");
}
}
public class Main{
public static void main(String[] args) {
MyThread my=new MyThread();
th.start();
System.out.println(“main method");
th.start();
}
}
Now two separate thread will be created main thread and child thread and result may vary between start() method followed by main method
followed by run method
Runnable Interface
• Thread class implements Runnable interface
• So it could be stated as MyThreadThreadRunnable
• Second approach could be MyRunnableRunnable
• That means we can define a thread by implementing runnable
interface.
• Runnable interface is in java.lang package and contains only one
method run(). Public void run()
Runnable Interface Example
class MyTest implements Runnable int i=1;
{ while(true) {
public void run() System.out.println(i+"World");
{ i++;
}
int i=1;
}
while(true) }
{ Th.start() will call thread class run method..but we want run()
System.out.println(i+"Hello"); method of MyTest to execute so object of class that implement
i++; runnable will be passed as arg.
}
}
}
public class Test {
public static void main(String[] args) throws Exception{
// TODO code application logic here
MyTest t=new MyTest();
Thread th=new Thread(t);
class MyRunnable implements Runnable
{
public void run()
{
System.out.println(“child thread");
}
}
public class Test {
public static void main(String[] args) throws Exception{
MyRunnable r1=new MyRunnable();
Thread th1=new Thread();
Thread th2=new Thread(r1);
th1.start();// a new thread will be created and Thread class run() method will be called
th1.run(); //No new thread will be created and Thread class run() method will be called
th2.start();//a new thread will be created and MyRunnable run() method will be called
th2.run();// no new thread will be created and MyRunnable run() will be called
r1.start();//in MyRunnable there is no start method so compile time error will be generated: can not find symbol method
start()
r1.run();//MyRunnable run() will be executed like a normal function call and without creating separate thread
}
}
Another Way
int i=1;
public class Test implements Runnable{ while(true)
public void run() {
{ System.out.println(i+"World");
i++;
int i=1;
}
while(true) }
{ }
System.out.println(i+"Hello");
i++;
}
}
public static void main(String[] args) throws Exception{
// TODO code application logic here
Test t=new Test();
Thread th=new Thread(t);
th.start();
Another Example
import java.util.*;
class MyThread implements Runnable{
public void run() {
for(int i=0;i<10;i++) {
System.out.println("World");
}
}
}
public class Main{
public static void main(String[] args) {
MyThread my=new MyThread();
Thread th=new Thread(my);
th.start();
int j=1;
for(int k=0;k<10;k++){
System.out.println("Hello");
}
}
Calling run() method explicitly
import java.util.*;
class MyThread implements Runnable{
public void run() {
for(int i=0;i<10;i++) {
System.out.println("World");
}
}
}
public class Main{
public static void main(String[] args) {
MyThread my=new MyThread();
Thread th=new Thread(my);
th.run();
int j=1;
for(int k=0;k<10;k++){
System.out.println("Hello");
}
}
}
• To create a thread implementing runnable interface is recommended
since by using extending thread is already extending one class so
there is no scope of extending another class. By implementing
runnable interface we can extend other class as well.
State of a Thread
Mythread t
=new Thread scheduler
Mythread() allocated
t.start() processor run()
Ready/
New Running Terminated
Runnable
notify()
wait()
Sleep Request I/O
wait
wait blocked
Timed wait
Thread Priorities
CPU
Scheduler
===============================
JVM
--------------------------------------------------
Operating System
Thread Priorities
• Threads can have priorities. In case a program have more than one
thread then they will be in ready queue.
• Ready queue is maintained by JVM which is further handles by a
component named scheduler
• Since CPU can execute one thread at a time so scheduler will schedule
threads for execution and provide them equal amount of time for
execution.
• If any thread has higher priorities then in that case thread will not be
executed in same round robin fashion. Thread having higher priority
will get executed first.
Thread Priorities
• In java minimum thread priority is 1 and maximum in 10.
• Thread.MIN_PRIORITY=1
• Thread.NORM_PRIORITY=5
• Thread.MAX_PRIORITY=10
• Normally it starts with priority 5 and programmer can increase or
decrease priority accordingly.
• Example: Microsoft word, spell checker and autosave.
• Pulling the data from internet and displaying is priority rather than
displaying the add or animation etc.
• Multithreading feature is provided by operating system but java has
its own multi-threading environment. It may take help of OS also.
• JVM or JRE has its own scheduler, it may take help of OS but they are
scheduled by java runtime environment.
• Scheduler will schedule the execution of thread since multiple threads
are available to execute. In what sequence thread will be scheduled
depends on scheduler. Some scheduler may go with round robin,
some may go for SJF (Shortest Job First).
Thread class
• Constructor
• Thread(): default constructor of thread class, Thread t=new Thread();
• But whenever any thread is created then JRE or JVM will give any ID or name so that it can be
recognized
• Thread(Runnable r): here argument is runnable interface, since runnable interface needs a
thread to execute.
Thread t=new Thread(runnable r)
• Thread(String name): you can assign the name of the thread
Thread t=new Thread(String name)
• Thread(Runnable r, String name): here the second interface is name of thread
• Thread(ThreadGroup g, String name): we can create a group of thread and can pass it to thread
group. e.g. pausing a game.
• Thread(ThreadGroup g, Runnable r)
• Thread(ThreadGroup g, Runnable r, String name):
import java.util.*;
class MyThread extends Thread{
public void run() {
System.out.println("child thread");
}
}
public class Main{
public static void main(String[] args) {
MyThread th1=new MyThread();
Thread t=new Thread(th1);
t.start();
System.out.println("main method");
}
}
// Thread t=new Thread(th1); it takes MyThread object as argument whereas the constructor of thread class accept
Runnable object as argument..this is acceptable since MyThreadThreadRunnable so we can take MyThread class
Thread class
• getter()/setter()
• Long getId()
• String getName()
• Int getPriority()
• ThreadState getState()
• ThreadGroup getThreadGroup()
• Void setName(String name)
• Void setPriority(int p)
• Void setDemon(Boolean b): daemon thread is background thread with least priority. Works in background.
e.g. GC
• Enquiry
• Boolean isAlive()
• Boolean isDaemon():
• Boolean isInterrupted(): to interrupt the thread. E.g. if a thread is waiting or sleeping then it can be
interrupt.
import java.util.*;
class MyThread extends Thread{
}
public class Main{
public static void main(String[] args) {
System.out.println(Thread.currentThread().getName());
MyThread th=new MyThread();
System.out.println(th.getName());
}
}
getName()
import java.util.*;
class MyThread extends Thread{
}
public class Main{
public static void main(String[] args) {
System.out.println(Thread.currentThread().getName()); MyThread
th=new MyThread();
System.out.println(th.getName());
Thread.currentThread().setName("Richa");
System.out.println(Thread.currentThread().getName());
}
}
• Instance Method
• Void interrupt()
• Void join(): once a thread has finished its job then it will get terminated. Instead of getting terminated it can
wait for other threads to complete so it can call join method for those threads. e.g. main() method start
other thread but once main() is finished and other threads are still working then main() should wait for
other thread to complete the process
• Void join(long millis): here thread can wait for few mentioned mili seconds
• Void run()
• Void start()
• Static Method
• Int activeCount(): it will mention the number of active thread count
• Thread currentThread(): reference to current thread
• Void yield(): when higher priority thread is taking more time then it will cause starvation for other thread.
So to handle this situation yield() will help to hold the higher priority thread for a while and let other thread
to execute.
• Void dumpStack(): the stack of an application.
Thread Priority
• Every thread has some priority. It may be default (provided by JVM) or provided by user.
• Valid range of priority 1-10
• Min-priority is denoted by Thread.MIN_PRIORITY 1
• Max Priority is denoted by 10 Thread.MAX_PRIORITY 10
• Normal priority is denoted by Thread.NORM_PRIORITY 5
• Thread having high priority will get chance to execute before
• Thread class define following methods to get and set priority of thread
• Public final int getPriority()
• Public final void setPriority(int p)
• Allowed values range in setPriority is 1-10 otherwise IllegalArgumentException will be thrown e.g.
th.setPriority is okay but th.setPriority(17) will throw exception
• Default Priority only for min thread is 5 but for all remaining threads default priority will be inherited from
parent to child i.e. whatever parent thread has the same priority will be there for the child thread
• If parent thread priority is 10 then child thread automatically will get priority 10
• Thread is created in main() thread
Thread Main Thread
Parent Thread
Parent Class
MyThread t=new
MyThread
Setting thread priority
import java.util.*;
class MyThread extends Thread{
}
public class Main{
public static void main(String[] args) {
System.out.println(Thread.currentThread().getPriority());
Thread.currentThread().setPriority(7);
MyThread th=new MyThread();
System.out.println(th.getPriority());//7
}
}
Some platforms won’t provide proper support for thread priorities so it may be possible that even
after setting the thread priority.
Ways to Prevent thread execution
• yield()
• join()
• sleep()
• Yield method causes to pause current executing thread to give the
chance for waiting threads of same priority
• If there is no waiting thread or all waiting threads are of low priority
then same thread can continue its execution
• Some platform does not provide support for yield() method. So we
cannot guarantee the behaviour even after adding yield().
Thread.yield()
Ready/
New Running Terminated
Runnable
Yield example
import java.util.*;
class MyThread extends Thread{
public void run() {
for(int i=0;i<10;i++) {
System.out.println("child thread");
Thread.yield();
}
}
}
public class Main{
public static void main(String[] args) {
MyThread th=new MyThread();
th.start();
for(int i=0;i<10;i++) {
System.out.println("Main thread");
}
}
Join() method
• If A thread wants to wait until completing some other thread then we
should go for join() method
• For example if a thread t1 wants to wait until completing t2 then t1 has
to call t2.join()
• Syntax public final void join()
• Public final void join(long ms): process will wait given ms time if other
process will not complete within the given time then the process will
continue its execution
• Public final void join(long ms, int ns):
• It throws interruptedException
Thread.yield()
Ready/
New Running Terminated
Runnable
T2.join()
T2.join(10)
T2.join(10,100)
Waiting
State
• Once a thread will go from running to waiting state then it will not come directly to running. It will
come to ready or runnable state if t2 will complete or if time completes or t2 will get interrupted
import java.util.*;
class MyThread extends Thread{
public void run() {
for(int i=0;i<10;i++) {
System.out.println("child thread");
try {
Thread.sleep(1000);
}
catch(InterruptedException e) {
e.getMessage(); }
}
}
}
public class Main{
public static void main(String[] args) {
MyThread th=new MyThread();
th.start();
try{ th.join(); }
catch(InterruptedException e){e.getMessage(); }
}
}
import java.util.*;
class MyThread extends Thread{
public void run() {
for(int i=0;i<10;i++) {
System.out.println("child thread");
try {
Thread.sleep(1000);
}
catch(InterruptedException e) {
e.getMessage(); }
}
}
}
public class Main{
public static void main(String[] args) {
MyThread th=new MyThread();
th.start();
try{ th.join(5000); }
catch(InterruptedException e){e.getMessage(); }
}
}
class MyRun extends Thread
{
public MyRun(String Name)
{
super(Name);
}
}
public class Test{
public static void main(String[] args) throws Exception{
MyRun t=new MyRun("My thread");
System.out.println("ID "+t.getId());
System.out.println("Name: "+t.getName());
System.out.println("Priority: "+t.getPriority());
System.out.println("State: "+t.getState());
System.out.println("Alive: "+t.isAlive());
}
}
class MyRun extends Thread
{
public MyRun(String Name)
{
super(Name);
}
}
public class Test{
public static void main(String[] args) throws Exception{
MyRun t=new MyRun("My thread");
System.out.println("ID "+t.getId());
System.out.println("Name: "+t.getName());
System.out.println("Priority: "+t.getPriority());
t.start();
System.out.println("State: "+t.getState());
System.out.println("Alive: "+t.isAlive());
}
}
class MyRun extends Thread public class Test{
{
public MyRun(String Name) public static void main(String[] args) throws Exception{
{ MyRun t=new MyRun("My thread");
System.out.println("ID "+t.getId());
super(Name);
System.out.println("Name: "+t.getName());
} System.out.println("Priority: "+t.getPriority());
public void run() t.start();
{ System.out.println("State: "+t.getState());
int count =1; System.out.println("Alive: "+t.isAlive());
while(true) }
}
{
System.out.println(count++);
try {
//it is a infinite loop which is fast and now we want to slow it down
Thread.sleep(10);
} catch (InterruptedException ex) {
System.out.println(ex);
}
}
}
}
}
}
}
}
public class Test{
class MyRun extends Thread
{ public static void main(String[] args) throws Exception{
public MyRun(String Name) MyRun t=new MyRun("My thread");
{ t.start();
super(Name); t.interrupt();
} }
public void run() }
{
int count =1;
while(true)
{
System.out.println(count++);
try {
//it is a infinite loop which is fast and now we want to slow it down
Thread.sleep(1000);
} catch (InterruptedException ex) {
System.out.println(ex);
Daemon, join and yield method
while(true)
{
System.out.println(count++ +"My thread");
}
}
}
Advantages of Java Multithreading
1) It doesn't block the user because threads are independent and you can
perform multiple operations at the same time.
2) You can perform many operations together, so it saves time.
3) Threads are independent, so it doesn't affect other threads if an
exception occurs in a single thread.