Unit 4
Unit 4
UNIT-IV
MULTITHREADED PROGRAMMING
Introduction, Creating Threads, Extending the Threads, Stopping and Blocking a Thread, Lifecycle
of a Thread, Using Thread Methods, Thread Exceptions, Thread Priority, Synchronization,
Implementing the ‘Runnable’ Interface.
MANAGING ERRORS AND EXCEPTIONS: Types of errors : Compile-time errors, Run-time errors,
Exceptions, Exception handling, Multiple Catch Statements, Using finally statement
MULTITHREADED PROGRAMMING
Multi-Processing Multi-Threading
Each process have its own address in Threads have same address space
memory
Process is heavy weight Thread is light weight
Cost of communication between the Cost of communication between the
process is high threads is low
class ThreadDemo
{
public static void main (String args[])
{
MyThread t1 = new MyThread( );
t1.start();
for (int i =1;i<10;i++)
{
System.out.println("Main Thread");
}
}
}
Output:
Main Thread
Main Thread
Main Thread
Main Thread
Main Thread
Main Thread
Main Thread
Main Thread
Main Thread
Child Thread
Child Thread
Child Thread
Child Thread
Child Thread
Child Thread
Child Thread
Child Thread
Child Thread
Child Thread
System.out.println("Child Thread");
}
}
}
class ThreadDemo
{
public static void main (String args[])
{
MyRunnable r = new MyRunnable();
Thread t1 = new Thread(r);
t1.start();
for (int i =1;i<10;i++)
{
System.out.println("Main Thread");
}
}
}
Output:
Main Thread
Main Thread
Main Thread
Main Thread
Main Thread
Main Thread
Main Thread
Main Thread
Main Thread
Child Thread
Child Thread
Child Thread
Child Thread
Child Thread
Child Thread
Child Thread
Child Thread
Child Thread
Child Thread
Sleep
• a thread can be made to sleep for a specified time period using sleep(time)
• The thread re-enters the runnable state as soon as the time period is elapsed
Wait
• A thread can be made to wait until some event occurs by using wait( ) method
• The thread can be scheduled to run again using notify( )method
Runnable State
➢ It means that the thread is ready for execution and is waiting for the availability
of processor
➢ If all threads have equal priority then they are given time slots for execution in
first come first serve manner
➢ If a thread want to give up the control to another thread to equal priority before
its turn comes, then call yield ( )method
7
Running State
It means that the processor has given its time to the thread for its execution
• Suspend – the thread can be suspended using suspend() method and can be
set into runnable state by using resume( ) method
• Sleep - a thread can be made to sleep for a specified time period using
sleep(time)
The thread re-enters the runnable state as soon as the time period is elapsed
• Wait – A thread can be made to wait until some event occurs by using wait( )
method
The thread can be scheduled to run again using notify( )method
Blocked state
• A thread is said to blocked when it is prevented from entering into runnable
state
• This happens when thread is suspend, sleeping or waiting in order to satisfy
certain requirements
Dead State
• A running thread ends its life when it has completed executing its run( )method
Synchronized method
➢ Used to solve data inconsistency
➢ Synchronized is the modifier applicable for methods and blocks
➢ Synchronized keyword in java creates a block of code known as Critical Section
➢ To enter a critical section, a thread needs to obtain the corresponding lock
Syntax:
synchronized(sync_obj)
{
}
9
Ex:
public class SynchronizedCounter
{
private int c = 0;
public synchronized void increment()
{
c++;
}
public synchronized void decrement()
{
c--;
}
public synchronized int value()
{
return c;
}
}
Synchronized blocks
➢ A synchronized statement can be used to acquire a lock on any object
➢ When executing a block of code in a method
public void addName(String name)
{
synchronized (this)
{
lastName = name;
nameCount++;
}
nameList.add(name);
}
Syntax:
try
{
statements //generates an exception
}
catch(Exception e)
{
Statements //processes the exception
}
try
➢ a keyword try preface a block of code that is likely to cause an error condition
➢ if one statement in try block generates an exception, the remaining statements
are skipped and jumps to catch block
catch
➢ the catch block process the exception
➢ catch statement is passed a single parameter which is reference to exception
object thrown
➢ if catch parameter matches with the type of exception object, then the exception
is caught and statements in catch block will be executed.
➢ If exception is not caught and the default exception handler will cause the
execution to terminate
//program to show the concept of try catch mechanism
public class Exception1
{
public static void main(String args[])
{
try
{
Scanner s = new Scanner(System.in);
System.out.println("Enter value");
int x = s.nextInt();
int k = 44 /x;
System.out.println("The value of k is "+k);
}
catch(ArithmeticException ae)
{
System.out.println("Please enter non zero value");
}
}
}
}
finally
{
2)
try
{
}
catch()
{
}
13
.
.
finally
{
}