0% found this document useful (0 votes)
1 views35 pages

10.Java MultiThreading

The document provides a comprehensive overview of multithreading in Java, covering key concepts such as thread creation, lifecycle, synchronization, and exceptions. It explains the difference between multitasking and multithreading, details the methods and classes involved in thread management, and discusses thread groups and synchronization techniques. Additionally, it highlights the importance of thread safety and inter-thread communication for effective multithreaded programming.

Uploaded by

Bc career
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1 views35 pages

10.Java MultiThreading

The document provides a comprehensive overview of multithreading in Java, covering key concepts such as thread creation, lifecycle, synchronization, and exceptions. It explains the difference between multitasking and multithreading, details the methods and classes involved in thread management, and discusses thread groups and synchronization techniques. Additionally, it highlights the importance of thread safety and inter-thread communication for effective multithreaded programming.

Uploaded by

Bc career
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 35

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

For Better utilization of CPU, multitasking can be


achieved on following basis

∗ Process Based (Multiprocessing)

∗ Thread Based (Multithreading)


Sharing of Address Space
Threads Concept

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

∗ NEW :- A thread that has not yet started is in this state.


∗ RUNNABLE :- A thread executing in the Java virtual machine
is in this state.
∗ BLOCKED :- A thread that is blocked waiting for a monitor
lock is in this state.
∗ WAITING :- A thread that is waiting indefinitely for another
thread to perform a particular action is in this state.
∗ TIMED_WAITING:- A thread that is waiting for another
thread to perform an action for up to a specified waiting
time is in this state.
∗ TERMINATED :- A thread that has exited is in this state.
Thread Creation

∗ Thread can be created by two ways in java

∗ Extending Thread Class

∗ Implementing Runnable Interface


The Thread Class
«interface»
java.lang.Runnable

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

∗ void start():-This method causes this thread to begin


execution; the Java Virtual Machine calls the run method of
this thread.
∗ sleep(long millis):- his method causes the currently
executing thread to sleep (temporarily cease execution) for
the specified number of milliseconds.
∗ run():-If this thread was constructed using a separate
Runnable run object, then that Runnable object's run
method is called; otherwise, this method does nothing and
returns.
∗ join(long millis):- Waits at most millis milliseconds for this
thread to die.
Extending Thread Class

public class MyThread extends Thread {


public void run(){ System.out.println("MyThread
running");
}
public static void main(String arg[]){
MyThread mt = new MyThread();
mt.start();
}
}
Implementing Runnable

public class MyRunnable implements Runnable { public void


run(){ System.out.println("MyRunnable");
}
public static void main(String arg[]){
MyRunnable mr = new MyRunnable();
Thread t = new Thread(mr);
t.start();
}
}
Thread class Constructors

•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

ThreadGroup tg1 = new ThreadGroup("Group A");

Thread t1 = new Thread(tg1,new MyRunnable(),“1");


Thread t2 = new Thread(tg1,new MyRunnable(),“2");

Thread t3 = new Thread(tg1,new MyRunnable(),“3");

// MyRunnable is a class that implement Runnable Interface


public class DemoThreadGroup implements Runnable{
public void run() {
System.out.println(Thread.currentThread().getName());
}
public static void main(String[] args) {
DemoThreadGroup MyRunnable = new DemoThreadGroup();
ThreadGroup tg1 = new ThreadGroup(“Group A");
Thread t1 = new Thread(tg1, MyRunnable,“1");
t1.start();
Thread t2 = new Thread(tg1, MyRunnable,“2");
t2.start();
Thread t3 = new Thread(tg1, MyRrunnable,“3");
t3.start();
System.out.println("Thread Group Name: "+tg1.getName());
tg1.list();
}
}
Unsafe Thread Operations
Array
Object

Read Read Write Write


Synchronized Access
Array
Object

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();
}

public void run() {


synchronized (ct) { ct.palyMatch(teams, win);
ct.print("Hello ", " Come In..."); }
}
Example: Synchronized Block
public static void main(String[] args) {
CricketMatch ct=new CricketMatch();
SycnBlock s=new SycnBlock("India VS Australia", "India", ct);
SycnBlock s1=new SycnBlock("W.I VS Pak", "PAK", ct);
SycnBlock s2=new SycnBlock("CheniSprKng VS MI ", "MI", ct);
}
}

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

Inter-thread communication or Co-operation


allows synchronized threads to communicate
with each other using following methods of
Object Class.

wait()
notify()
notifyAll()

You might also like