0% found this document useful (0 votes)
8 views13 pages

Unit 4

The document provides an overview of multithreaded programming in Java, including concepts such as thread creation, lifecycle, synchronization, and error handling. It explains the differences between multithreading and multiprocessing, methods for creating threads, and the importance of exception handling in managing runtime errors. Additionally, it covers thread priority, synchronization techniques, and the use of try-catch blocks for error management.

Uploaded by

karanambharathi
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)
8 views13 pages

Unit 4

The document provides an overview of multithreaded programming in Java, including concepts such as thread creation, lifecycle, synchronization, and error handling. It explains the differences between multithreading and multiprocessing, methods for creating threads, and the importance of exception handling in managing runtime errors. Additionally, it covers thread priority, synchronization techniques, and the use of try-catch blocks for error management.

Uploaded by

karanambharathi
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/ 13

1

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

Q) Explain the concept of Thread


➢ Multithreading refers to two or more tasks executing concurrently with in a
single program
➢ A thread is similar to a program that has single flow of control
➢ It has beginning, a body and an end and executes commands sequentially
➢ Every program will have atleast one thread
➢ Many threads can run concurrently with in a program
➢ Every thread in java is created and controlled by java.lang.Thread class
Ex: Single Threaded Program

Concept of Multi threading

➢ Multi threading is a powerful tool and can be used in multiple ways


➢ Enables programmers to do multiple things at one time
➢ They can be divide a long program into threads and execute them in parallel
➢ Ex: printing the papers in the background and continue to perform some other
tasks like listening music, downloading movies etc.,
➢ Threads are used in Java enabled browsers such as Hot java
Q) What are the advantages of Threads
➢ Doesn’t block the user because threads are independent
➢ Can perform many operations together
2

➢ Saves the time


➢ It doesn’t affect other threads since they are independent

Q) Write the differences between Multiprocessing and Multi Threading

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

Q) Explain the creating, implementing and extending the threads in java


➢ There are two ways by which thread can be created in Java:
1. By extending Thread class
2. By implementing Runnable interface.
1. By extending Thread Class
➢ We can make our class run as Thread by extending the class java.lang.Thread
➢ We can access to all the thread methods directly
Steps:
1. Declare the class as extending the Thread class
2. Implement the run() method
3. Create a thread Object and call the start() method to initiate the execution
Syntax:
class MyThread extends Thread
{
}
➢ run () method has been inherited from Thread class
➢ Now we have to override the run method and code is written in the body of run()
Syntax:
public void run()
{
}
➢ Now the thread is started by creating its object
MyThread a = new MyThread();
a.start(); //invokes the run method
➢ start() method causing the thread to run by invoking run() method

//Program to show the concept of extending Thread class


class MyThread extends Thread
{
public void run()
{
for (int i = 1;i<=10;i++)
{
System.out.println("Child Thread");
}
}
}
3

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

2. Implementing the Runnable Interface


➢ Thread class is used for creating and running Threads
➢ Runnable Interface declares the run() method that is required for implementing
the threads in the program.
Steps:
1. Declare the class as implementing the Runnable interface
2. Implement the run( ) method
3. Create the thread by defining an object from “Runnable” interface
4. Call the thread start( ) method to run the thread.

Program to show the concept of implementing Runnable Interface


class MyRunnable implements Runnable
{
public void run()
{
for (int i = 1;i<=10;i++)
{
4

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

Q) Explain the stopping and blocking of a Thread


Stopping a Thread
➢ Whenever we want to stop a thread from running further, call a function stop( )
➢ This causes a thread to stop immediately and move it to its dead state
➢ It forces the thread to stop abruptly before its completion
Syntax: stop( )
Blocking a Thread:
➢ A thread can be temporarily suspended or blocked from entering into runnable
and subsequent running state
5

The methods are


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

➢ These methods cause the thread to go into blocked state

Q) Explain the life cycle of Thread


➢ A thread is always in one of the following states
➢ It can move from one state to another
➢ The states are
1. New born state
2. Runnable state
3. Running state
4. Blocked state
5. Dead state
6

New Born state


➢ Whenever a thread is created, it is born
➢ A new thread can do any of the following
o Scheduled it for running using start( ) method
o Kill it using stop( )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

Q) Explain Thread Priority in Java


➢ Each thread is assigned a priority
➢ By setting this, it affects the order in which it is scheduled for running
➢ If threads of same priority are given equal treatment by java scheduler.
➢ They share the processor on a First Come First Serve basis
➢ Syntax: ThreadName.setPriority(int);
➢ MIN_PRIORITY = 1 NORM_PRIORITY =5 MAX_PRIORITY =10
8

➢ The integer value should be between 1 and 10


//program to show the concept of Thread Priority
class TestMultiPriority1 extends Thread
{
public void run()
{
System.out.println("running thread name is:"+Thread.currentThread().getName());
System.out.println("running thread priorityis:"+Thread.currentThread().getPriority());
}
public static void main(String args[])
{
TestMultiPriority1 m1=new TestMultiPriority1();
TestMultiPriority1 m2=new TestMultiPriority1();
m1.setPriority(Thread.MIN_PRIORITY);
m2.setPriority(Thread.MAX_PRIORITY);
m1.start();
m2.start();
}
}

Q) Explain Synchronization in Java


➢ While working with multiple threads, it happens that more than one thread
wants to access the same variable at a same time
➢ Ex: one thread might try to read the data, while other thread tries to change the
data
➢ In such cases, we need to allow one thread to finish its task completely and
allow the next thread to execute.
➢ The process by which this is achieved is called “Synchronization”.
➢ This can be attained in java by using a keyword “synchronized”
➢ The key to synchronization is the concept of “monitor or lock”
➢ Only one thread can own a monitor at a given time
➢ When a thread acquire a lock, it is said to have entered a monitor
➢ All other threads attempting to enter the locked monitor will be suspended until
the first thread exits the monitor

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

MANAGING ERRORS AND EXCEPTIONS

Q) Explain the types of errors


➢ Errors may broadly be classified into 2 categories
1. Compile time
2. Run time
1. Compile Time Errors
➢ All syntax errors will be detected and displayed by java Compiler
➢ Such errors are known as Compile time errors
➢ Whenever a compiler displays an error, it will not create a byte code file or
.class file
➢ After fixing all the errors before compiling, compiler creates .class file and runs
the program
Ex: System.out.println(“Hello Welcome to Java)//Error:no ending quotes and missing ;
➢ Most common problems are
o Missing semi colons
o Missing brackets
o Misspelling of keywords
o Missing double quotes
10

2. Run time errors


➢ A program may compile successfully creating the .class file but may not run
properly
➢ Such program may produce wrong results
➢ Most common runtime errors
o Dividing an integer by zero
o Accessing an element out of bounds of an array
o Attempting to use a negative size for an array
o Converting invalid String to a number
//program to show the concept of Runtime error
import java.util.Scanner;
public class Exception2
{
public static void main(String args[])
{

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);
}
}
Output:
Enter value
0
Exception in thread "main" java.lang.ArithmeticException: / by zero
at Exception2.main(Exception2.java:10)

Q) Explain exception Handling in Java


➢ An exception is a condition that is caused by runtime error in a program
➢ When java interpreter encounters an error such as dividing an integer by zero,
it creates an exception object and informs us that an error has occurred
➢ If we want the program to continue with the execution without terminating the
program, we should try to catch the exception object thrown by error condition
➢ Display an appropriate message for corrective actions
➢ This task is known as Exception Handling
Mechanism of Exception Handling
1. Find the problem (Hit the exception)
2. Inform that an error has occurred (Throw the exception)
3. Receive the error information (catch the exception)
4. Take corrective actions (Handle the Exception)
Error Handling Code
➢ It contains two segments
o To detect errors and to throw exceptions
o To catch exceptions and to take necessary actions
11

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

Q) Explain multiple catch statements


➢ It is possible to have more than one catch statement in catch block
➢ When an exception in try block is generated, java treats the multiple catch
statements like cases in a switch statement
➢ The first statements whose parameters matches with the exception object will
be executed and the remaining statements will be skipped
12

//program to show the concept of multiple catch statements


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");
}
catch(InputMismatchException ime)
{
System.out.println("Please enter non integer value");
}
}
}

Q) Explain finally block in java


➢ Java supports another statement known as finally
➢ Used to handle an exception that is not caught by any of the previous catch
statements
➢ Used to handle any exception generated with in a try block
➢ Can be added immediately after the try block or after the last catch block
➢ When defined, this is guaranteed to execute whether an exception is raised or
not.
Syntax:
1)
try
{

}
finally
{

2)
try
{
}
catch()
{
}
13

.
.
finally
{
}

//Program to show the concept of finally keyword


import java.util.*;
public class Exception2
{
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");
}
catch(InputMismatchException ime)
{
System.out.println("Please enter non integer value");
}
finally
{
System.out.println("Connections closed");
}
System.out.println("End of the program");
}
}
Output:
Enter value 7.8
Please enter non integer value
Connections closed
End of the program

You might also like