0% found this document useful (0 votes)
75 views27 pages

Multi Threaded Programming

java

Uploaded by

mattdmn
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPS, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
75 views27 pages

Multi Threaded Programming

java

Uploaded by

mattdmn
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPS, PDF, TXT or read online on Scribd
You are on page 1/ 27

MULTITHREADED

PROGRAMMING
Introduction
Thread: A sequence of instructions executed
within the context of a process.
A program that contains multiple flows of control
is known as multithreaded program.
Multithreaded is a conceptual programming
paradigm where a program (process) is divided
into two or more subprograms (processes), which
can be implemented at the same time in parallel.
Concurrency And Lightweight Thread
Concurrency : A condition that exists when at
least two threads are making progress. A more
generalized form of parallelism that can include
time-slicing as a form of virtual parallelism.

Lightweight Thread or Lightweight


processes(LWP) : Kernel threads, also called
LWPs, that execute kernel code and system calls.
LWPs are managed by the system thread
scheduler, and cannot be directly controlled by the
application programmer. This is known as a 1:1
thread model.
A Multithreaded program
Main Thread

Main method
module

start start start

switching switching

Thread A Thread B Thread C


Creating Threads
Threads are implemented in the form of objects that
contain a method called run( ).
The run( ) method is the is the heart and soul of any
thread.
public void run( ){
…………
…………(statements for implementing thread)
………..
}
The run( ) method should be invoked by an object of the
concerned thread.
This can be achieved by creating the thread and initiating
it with the help of another thread method called start ().
Two ways for creating Thread
By creating a thread class :
Define a class that extends Thread class and override
its run() method with the code required by the
thread.

By converting a class to a thread :


Define a class that implements Runnable interface.
The Runnable interface has only one method,
run( ), that is to be defined in the method with code
to be executed by the thread.
Extending the Thread Class
We can make our class runnable as thread by
extending the class java.lang.Thread.
This gives us access to all the thread methods
directly. It includes the following steps:
1. Declare the class as extending the Thread class.
2. Implement the run( ) method that is responsible for
executing the sequence of code that the thread will
execute.
3. Create a thread object and call the start( ) method to
initiate the thread execution.
Creating threads using the thread
class
class A extends Thread {
public void run( ){
for(int i=1; i<=5; i++){
System.out.println(“\t From thread A : i = ” + i);
}
System.out.println(“Exit from A ”);
}
}
class B extends Thread{
public void run( ){
for(int j=1; j<=5; j++){
System.out.println (“\t From thread B : j = ” + j);
}
System.out.println(“Exit from B”);
}
} (Continued)
Creating threads using the thread class
(Continued)
class C extends Thread{
public void run( ){
for(int k=1; k<=5; k++){
System.out.println(“\tFrom Thread C : k = ” +k);
}
System.out.println(“Exit from C”);
}
}
class ThreadTest{
public static void main(String args[ ]){
new A( ).start( );
new B( ).start( );
new C( ).start( );
}
}
Output
From Thread A : i = 1
From Thread A : i = 2
From Thread B : j = 1
From Thread B : j = 2
From Thread C : k = 1
From Thread C : k = 2
From Thread A : i = 3
From Thread A : i = 4
From Thread B : j = 3
From Thread B : j = 4
From Thread C : k = 3
From Thread C : k = 4
From Thread A : i = 5 Exit from A
From Thread B : j = 5 Exit from B
From Thread C : k = 5 Exit from C
Life Cycle of a Thread
New Thread Newborn
stop
start

Active stop Killed


Running Runnable Dead
Thread Thread
yield

suspend resume
sleep notify
wait
stop

Idle Thread Blocked


(Not Runnable)
Newborn State
When we create a thread object, the thread is born and is
said to be in newborn state. The thread is not yet
scheduled for running. At this state, we can do only one
of the following things with it:
Schedule it for running using start( ) method.
Kill it using stop( ) method.

Newborn

Runnable Dead
state state
Runnable State
The runnable state means that the thread is ready for
execution and is waiting for the availability of the
processor.
That is, the thread has joined the queue of threads that
are waiting for execution.
If all threads have equal priority, than they are given
time slots for execution in round robin fashion.
The process of assigning time to threads is known as
time-slicing
yield

Running
Thread

Runnable Threads
Running State
Running means that the processor has given its time
to the thread for its execution.
The thread runs until it relinquishes control on its
own or it is preempted by a higher priority thread.

suspend, sleep(t), wait

resume, after(t)
notify

Running Runnable Suspended, Waiting


Blocked State
A thread is said to be blocked when it is prevented
from entering into the runnable state and
subsequently the running state.
This happens when the thread is suspended,
sleeping, or waiting in order to satisfy certain
requirements.
A blocked thread is considered “not runnable” but
not dead and therefore fully qualified to run again
Dead State
A running thread ends its life when it has
completed executing its run( ) method.
It is a natural death.
However, we can kill it by sending the stop
message to it at any state thus causing a premature
death to it.
A thread can be killed as soon it is born, or while it
is running, or even when it is in “not runnable”
(blocked) condition.
Use of yield(), stop(), and sleep()
methods
class A extends Thread{
public void run( ){
for(int i = 1; i<=5; i++){
if(i==1) yield()
System.out.println(“\tFrom Thread A : i = ” +i)
}
System.out.println(“exit from A ”);
}
}
class B extends Thread{
public void run( ){
for(int j = 1; j<=5; j++){
System.out.println(“\tFrom Thread B: j = ” +j);
if(j==3) stop( );
}
System.out.println(“exit from B”);
}
} (Continued)
Use of yield(), stop(), and sleep() methods
(continued)
class C extends Thread{
public void run( ){
for(int k=1; k<=5; k++){
System.out.println(“\tFrom Thread C : k = ” +k);
if(k==1)
try{
sleep(1000);
}
catch(Exception e){ }
}
System.out.println(“Exit from C”);
}
} (continued)
Use of yield(), stop(), and sleep() methods
(continued)
Class ThreadMethods{
public static void main(String args[ ]){
A threadA = new A( );
B threadB = new B( );
C threadC = new C( );
System.out.println(“Start thread A”);
threadA.start( );
System.out.println(“Start thread B”);
threadB.start( );
System.out.println(“Start thread C”);
threadC.start( );
System.out.println(“End of main thread”);
}
}
Output
Start thread A
Start thread B
Start thread C
From Thread B : j = 1
From Thread B : j = 2
From Thread B : i = 1
From Thread B : i = 2
End of main thread
From Thread C : k = 1
From Thread B : j = 3
From Thread A : i = 3
From Thread A : i = 4
From Thread A : i = 5
Exit from A
From Thread C : k = 2
From Thread C : k = 3
From Thread C : k = 4
From Thread C : k = 5
Exit from C
Thread Exceptions
 Java run system will throw IllegalThreadStateException whenever we attempt to invoke a
method that a thread cannot handle in the given state.

 The catch statement may take one of the following forms:

catch (ThreadDeath e){


…….. // killled thread
}
catch (InterruptedException e){
…….. //cannot handle it in the current state
}
catch (IllegalArgumentException e){
…….. //Illegal method argument
}
catch (Exception e){
…….. //Any other
}
Thread Priority
The thread of the same priority are given equal
treatment by the Java scheduler and, therefore, they
share the processor on a first-come, first-serve basis.
Java permits us to set the priority of a thread using the
setPriority( ) method as follows
ThreadName.setPriority(int Number);
The intNumber is an integer value to which the thread’s
priority is set. The Thread class defines several priority
constants:
MIN_PRIORITY = 1
NORM_PRIORITY = 5
MAX_PRIORITY = 10
Synchronization
 If one thread may try to read a record from a file while
another is still writing to the same file, we may get strange
results.
 Java enables us to overcome this problem using a technique
known as synchronization.
 The keyword synchronized helps to solve such problems by
keeping a watch on such locations.
synchronized void update( ){
…….. //code here is synchronized
}
 It is also possible to mark a block of code as synchronized as
shown below:
synchronized (lock-object){
…….. //code here is synchronized
}
Deadlock in Thread
 An interesting situation may occur when two or more threads are waiting to gain
control of a resource. Due to some reasons, the condition on which the waiting
threads rely on to gain control does not happen. This results in what is known as
deadlock.
 Example: assume that the thread A must access Method1 before it can release
Method2, but the thread B cannot release Method1 until it gets hold of
Method2.because these are mutually exclusive conditions, a deadlock occurs.
Thread A
synchronized method2( ){
synchronized method1( ){
…………
}
}
Thread B
synchronized method1( ){
synchronized method2( ){
…………
}
}
Implementing the ‘Runnable’
Interface
The Runnable interface declares the run( ) method
that is required for implementing threads in our
programs. To do this, the steps are.
1. Declare the class as implementing the Runnable
interface.
2. Implement the run( ) method.
3. Create a thread by defining an object that is
instantiated from this “runnable” class as the target
of the thread.
4. Call the thread’s start( ) method to run the thread.
Using Runnable interface
class X implements Runnable{ //Step 1
public void run( ){ //Step 2
for(int i = 1; i<=10; i++){
System.out.println(“\tThreadX : ”+i);
}
System.out.println(“End of ThreadX”);
}
}
class RunnableTest{
public static void main(String args[ ]){
X runnable = new x( );
Thread threadX = new Thread(runnable); //Step 3
threadX.start( ); //Step 4
System.out.println(“End of main thread”);
}
}
Output
End of main Thread
ThreadX : 1
ThreadX : 2
ThreadX : 3
ThreadX : 4
ThreadX : 5
ThreadX : 6
ThreadX : 7
ThreadX : 8
ThreadX : 9
ThreadX : 10
End of ThreadX

You might also like