10.Java MultiThreading
10.Java MultiThreading
By : gaurav tiwari
Topics Covered
∗ Multitasking
∗ Introduction to Threads
∗ Thread Lifecycle
∗ Thread Creation
∗ Thread Class Methods
∗ Exceptions Possible
∗ Thread Joining
∗ Thread Group
∗ Unsafe Thread Operations
∗ Thread Synchronization
MultiTasking
Multiple Thread 1
threads on Thread 2
multiple Thread 3
CPUs
Multiple Thread 1
threads Thread 2
sharing a Thread 3
single CPU
What is Thread ?
∗ Definition :- A thread is a single sequential flow of control with
in a program
∗ Threads are lightweight processes; they share the same address
space. In Multithreaded environment, programs make
maximum use of CPU so that the idle time can be kept to
minimum.
∗ The main purpose of multithreading is to provide simultaneous
execution of two or more parts of a program to maximum
utilize the CPU time. A multithreaded program contains two or
more parts that can run concurrently. Each part of such a
program called a thread. Each thread has a separate path of its
execution. So this way a single program can perform two or
more tasks simultaneously.
Execution of Threads
1. Stacks are created for each thread
2. CPU cycles switches between these stacks
Thread Life Cycle
Thread State
java.lang.Thread
+Thread() Creates a default thread.
+Thread(task: Runnable) Creates a thread for a specified task.
+start(): void Starts the thread that causes the run() method to be invoked by the JVM.
+isAlive(): boolean Tests whether the thread is currently running.
+setPriority(p: int): void Sets priority p (ranging from 1 to 10) for this thread.
+join(): void Waits for this thread to finish.
+sleep(millis: long): void Puts the runnable object to sleep for a specified time in milliseconds.
+yield(): void Causes this thread to temporarily pause and allow other threads to execute.
+interrupt(): void Interrupts this thread.
Some important Method of Thread class
•Thread()
•Thread(String name)
•Thread(Runnable r)
•Thread(Runnable r,String name)
Thread Class other important Methods
∗ currentThread() • yield()
∗ getPriority() • suspend()
∗ setPriority() • resume()
∗ getName() • stop()
∗ setName() • setDaemon()
∗ getId() • isDaemon()
∗ getState() • join()
∗ isAlive()
Exceptions Possible
∗ InterruptedException
∗ IllegalThreadStateException
Joining Threads
The join() method is used to hold the execution of
currently running thread until the specified thread is
dead(finished execution).
join() Method
public static void main(String arg[]){
Thread t1 = new Thread(RO);
Thread t2 = new Thread(RO);
t1.start(); t2.start();
try{
ti.join();
t2.join();
}catch(Exception e){
System.out.println(e);
}
}
Thread Group
∗ Java provides a convenient way to group multiple
threads in a single object.
∗ We can suspend, resume or interrupt group of
threads by a single method call.
Constructors of ThreadGroup class
1) ThreadGroup(String name) creates a thread group with given
name.
2) ThreadGroup(ThreadGroup parent, String name) creates a thread group with given
parent group and name.
∗ Methods of ThreadGroup class
No Method Description
.
1) int activeCount()returns no. of threads running in current
group.
2) int returns a no. of active group in this thread
activeGroupCount group.
()
3) void destroy() destroys this thread group and all its sub
groups.
4) String getName() returns the name of this group.
5) ThreadGroup returns the parent of this group.
getParent()
6) void interrupt() interrupts all threads of this group.
7) void list() prints information of this group to
standard console.
Thread Group
Read
Write
Write
Read
Thread Synchronization
Synchronization: - Thread synchronization is the concurrent execution of two or more
threads that share critical resources.
When two or more thread within same program trying to access the same resource and
finally they can produce unforeseen result due to concurrency issue.
For example if multiple threads try to write within a same file then they may corrupt the
data because one of the threads can overwrite data or while one thread is opening the
same file at the same time another thread might be closing the same file.
For this situation we need synchronization for action of multiple threads and make sure
that only one thread can access the resource at a given point in time. This is
implemented using a concept called monitors.
Each object in Java is associated with a monitor, which a thread can lock or unlock. Only
one thread at a time may hold a lock on a monitor.
Thread Synchronization
∗ Java programming language provides two basic synchronization
idioms:
∗ Synchronized method.
∗ Synchronized block.
Mutual Exclusion
∗ Synchronized Methods
∗ Method can be invoked by a single thread at a time.
∗ Other thread wants to invoke it, will have to wait till the current
working thread finishes it.
∗ Synchronized Blocks
∗ An object is confined to a specific block
∗ Operation applied over this object will be synchronized
∗ Static Synchronization
∗ make any static method as synchronized.
∗ The lock will be on the class not on object.
Example: Synchronized Methods
public class SyncMethod extends Thread {
String gname,msg;
public SyncMethod(String gname,String msg) {
this.gname=gname;
this.msg=msg;
start(); }
public void run() {
WelcomeMessage.print(gname, msg);
WelcomeMessage.print1("Ram", "getOut");
}
public static void main(String[] args) {
SyncMethod s=new SyncMethod("Mr R Ramnam",
"Welcome to CMC Day ");
SyncMethod s1=new SyncMethod("Miss Mayawati",
"Welcome to Uttar Pradesh ");
}}
Example: Synchronized Methods
class WelcomeMessage
{public synchronized static void print(String guestName,String msg)
{ System.out.print(guestName);
try { Thread.sleep(500); }
catch (InterruptedException e) { e.printStackTrace(); }
System.out.println(" "+msg);
}
public static void print1(String str1,String str2)
{ System.out.print(str1);
try { Thread.sleep(1000); }
catch (InterruptedException e) { e.printStackTrace(); }
System.out.println(str2);
}
}
Example: Synchronized Block
public class SycnBlock extends Thread{
CricketMatch ct;
String teams,win;
public SycnBlock(String teams,String win,CricketMatch ct)
{ this.teams=teams;
this.win=win;
this.ct=ct;
start();
}
class CricketMatch
{ public void palyMatch(String teams,String win)
{ System.out.print("Match Between "+teams );
try {Thread.sleep(1000); }
catch (InterruptedException e) { e.printStackTrace(); }
System.out.println(" Wining Team "+win);
}
Example: Synchronized Block
public synchronized void print(String str1,String str2)
{
System.out.print(str1);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(str2);
}
}
Inter Thread Communication
wait()
notify()
notifyAll()