Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Unit III

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 38

UNIT III

EXCEPTION HANDLING AND MULTITHREADING


Exception handling basics – Multiple catch Clauses – Nested try Statements – Java’s Built-in
Exceptions – User defined Exception. Multithreaded Programming: Java Thread Model–
Creating a Thread and Multiple Threads – Priorities – Synchronization – Inter Thread
Communication- Suspending –Resuming, and Stopping Threads –Multithreading. Wrappers
– Auto boxing.

Exception Handling
Basics
Exception:

 Dictionary Meaning: Exception is an abnormal condition.

 In Java, an exception is an event that disrupts the normal flow of the program. It is an
object which is thrown at runtime.

Exception Handling:

The Exception Handling in Java is one of the powerful mechanism to handle the runtime
errors so that the normal flow of the application can be maintained.

Advantage of Exception Handling

The core advantage of exception handling is to maintain the normal flow of the
application. An exception normally disrupts the normal flow of the application; that is why
we need to handle exceptions. Let's consider a scenario:

1. statement 1;
2. statement 2;
3. statement 3;
4. statement 4;
5. statement 5;//exception occurs
6. statement 6;
7. statement 7;
8. statement 8;
9. statement 9;
10. statement 10;

Suppose there are 10 statements in a Java program and an exception occurs at statement 5;
the rest of the code will not be executed, i.e., statements 6 to 10 will not be executed.
However, when we perform exception handling, the rest of the statements will be executed.
That is why we use exception handling in Java.
Types of Java Exceptions

In Java, there are two types of exceptions:

1. Checked exceptions

 These are the exceptions that are checked at compile time.

 These types of exceptions can be handled at the time of compilation.

 These exceptions are extended from the java.lang.Exception class.

 These type of exceptions need to be handled explicitly by the code itself by


using the try-catch block or by using throws.

 Examples:

o IOException, SQLException, etc.

2. Unchecked exceptions

 These exceptions are checked at run-time.

 These type of exceptions need not to be handled explicitly.

 The Java Virtual Machine handles these type of exceptions.

 These exceptions are extended from java.lang.RuntimeException class.

 For example :
o ArrayIndexOutOfBounds,
o NullPointerException,
o RunTimeException.
Keywords used in exception handling
 try- The try block contains the code that might throw an exception.
 Catch- A catch block must be declared after try block. It contains the error handling
code. Note that for each corresponding try block there exists the catch block.
 finally- It specifies the code that must be executed even though exception may or may
not Occur.
 throw- For explicitly throwing the exception, the keyword throw is used.
 throws-The "throws" keyword is used to declare exceptions. It is always used with
method signature.
try-catch block:
 The statements that are likely to cause an exception are enclosed within a try block.
 There is another block defined by the keyword catch which is responsible for
handling the exception thrown by the try block.
 As soon as exception occurs it is handled by the catch block.
 The catch block is added immediately after the try block.
 Syntax:
try
{
//exception gets generated here

}
catch(Type_of_Exception e)
//exception is handled here
}
Example code for try-catch block
Java Program for try-catch block Output
public class TryCatchExample2 { java.lang.ArithmeticException: / by zero
rest of the code
public static void main(String[] args) {
try
{
int data=50/0; //may throw exception
}
//handling the exception
catch(ArithmeticException e)
{
System.out.println(e);
}
System.out.println("rest of the code");
}

Multiple catch clauses


 A try block can be followed by one or more catch blocks.
 Each catch block must contain a different exception handler.
 At a time only one exception occurs and at a time only one catch block is
executed.
Flowchart of Multi-catch Block
Syntax
try {
// Code block
}
catch (ExceptionType1 e1) {
// Handle ExceptionType1 exceptions
}
catch (ExceptionType2 e2) {
// Handle ExceptionType2 exceptions
}

Example code for multi-catch clauses


public class MultipleCatchBlock2 { ArrayIndexOutOfBounds Exception occurs
rest of the code
public static void main(String[] args) {

try{
int a[]=new int[5];

System.out.println(a[10]);
}
catch(ArithmeticException e)
{
System.out.println("Arithmetic Exception occurs");
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("ArrayIndexOutOfBounds
Exception occurs");
}
catch(Exception e)
{
System.out.println("Parent Exception occurs");
}
System.out.println("rest of the code");
}
}

Nested try statements


 In Java, using a try block inside another try block is permitted.
 It is called as nested try block.
Why use nested try block
Sometimes a situation may arise where a part of a block may cause one error and the entire
block itself may cause another error. In such cases, exception handlers have to be nested.
Program for Nested try block Output
class NestedtryDemo D:\>javac NestedtryDemo.java
{
public static void main(String[] args) D:\>java NestedtryDemo 20 10
{
try The result is 2
{
int a = Integer.parseInt (args [0]); D:\>java NestedtryDemo 20 a
int b = Integer.parseInt (args [1]);
int ans = 0; Incorrect type of data
try
{ D:\>java NestedtryDemo 20 0
ans = a/b;
System.out.println("The result is "+ans); Divide by zero
}
catch (ArithmeticException e)
{
System.out.println("Divide by zero");
}
}
catch (NumberFormatException e)
{
System.out.println ("Incorrect type of
data");
}
}
}

Java finally block


 Java finally block is always executed whether an exception is handled or not.
 The finally block follows the try-catch block.
 finally block in Java can be used to put "cleanup" code such as closing a file, closing
connection, etc.
 The important statements to be printed can be placed in the finally block.
Program for finally block Output
public class Demo java.lang.ArithmeticException: / by
{ zero
public static void main(String args[]) finally block is always executed
{ rest of the code...
try {
int data=25/0;
System.out.println(data);
}
catch(ArithmeticException e)
{
System.out.println(e);
}
finally {
System.out.println("finally block is always executed");
}
System.out.println("rest of the code...");
}
}

Using throw
 For explicitly throwing the exception, the keyword throw is used.
 The keyword throw is normally used within a method.
 We cannot throw multiple exceptions using throw.
Example for throw Output
class Test{ D:\one>javac Test.java
public static void main(String[] args)
{ D:\one>java Test
throw new ArithmeticException("/ by zero"); Exception in thread "main"
} java.lang.ArithmeticException: / by zero
} at Test.main(Test.java:4)

Using throws

When a method wants to throw an exception then keyword throws is used.


The syntax is
method_name(parameter_list) throws exception_list
{
}
Java Program for exception handling mechanism using Output
throws
class ExceptionThrows Caught exception:
{ java.lang.ArithmeticException: /by zero
static void fun(int a,int b) throws ArithmeticException
{
int c;
try
{
c=a/b;
}
catch(ArithmeticException e)
{
System.out.println("Caught exception: "+e);
}
}
public static void main(String args[])
{
int a=5;
fun(a,0);
}
}

Common Exception Scenarios

There are given some scenarios where unchecked exceptions may occur. They are as follows:

1) A scenario where ArithmeticException occurs

If we divide any number by zero, there occurs an ArithmeticException.

int a=50/0;//ArithmeticException

2) A scenario where NullPointerException occurs

If we have a null value in any variable, performing any operation on the variable throws a
NullPointerException.
1. String s=null;
2. System.out.println(s.length());//NullPointerException
3.
3) A scenario where NumberFormatException occurs

If the formatting of any variable or number is mismatched, it may result into


NumberFormatException. Suppose we have a string variable that has characters; converting
this variable into digit will cause NumberFormatException.

1. String s="abc";
2. int i=Integer.parseInt(s);//NumberFormatException

4) A scenario where ArrayIndexOutOfBoundsException occurs

When an array exceeds to it's size, the ArrayIndexOutOfBoundsException occurs. there may
be other reasons to occur ArrayIndexOutOfBoundsException. Consider the following
statements.

1. int a[]=new int[5];


2. a[10]=50; //ArrayIndexOutOfBoundsException
Java's Built-in Exceptions
• Various common exception types and causes are enlisted in the following table-
User defined Exception

• We can throw our own exceptions using the keyword throw.

• The syntax for throwing out own exception is

throw new Throwable's subclass

• Here the Throwable's subclass is actually a subclass derived from the Exception class.

For example -

throw new ArithmeticException();

Throwable's subclass
• Let us see a simple Java program which illustrates this concept.

Java Program[MyExceptDemo.java]

import java.lang.Exception;

class MyOwnException extends Exception

MyOwnException(String msg)

super(msg);

class MyExceptDemo

public static void main (String args[])

int age;

age=15;

try

if(age<21)

throw new MyOwnException("Your age is very less than the condition");

}
catch (MyOwnException e)

System.out.println ("This is My Exception block");

System.out.println (e.getMessage());

finally

System.out.println ("Finally block:End of the program");

Output

This is My Exception block

Your age is very less than the condition

Finally block:End of the program

Multithreaded Programming
Introduction to Thread
Definition: Thread
A thread is a lightweight sub-process that defines a separate path of execution. It is the
smallest unit of processing that can run concurrently with the other parts (other
threads)
of the same process.

Threads are independent.

If there occurs exception in one thread, it doesn't affect other threads.

It uses a shared memory area.

As shown in the above figure, a thread is executed inside the process.

There is context-switching between the threads.

There can be multiple processes inside the OS, and one process can have multiple
threads.
DIFFERENCE BETWEEN THREAD AND PROCESS:

PROCESS THREAD
 Process is a heavy weight program  Thread is a light weight process
 Each process has a complete set of its  Threads share the same data
own variables
 Processes must use IPC (Inter Process  Threads can directly communicate with
Communication) to communicate with each other with the help of shared
sibling processes variables
 Cost of communication between  Cost of communication between threads
processes is high. is low.
 Process switching uses interface in  Thread switching does not require
operating system. calling an operating system.
 Processes are independent of one  Threads are dependent of one another
another
 Each process has its own memory and  All threads of a particular process shares
resources the common memory and resources
 Creating & destroying processes takes  Takes less overhead to create and
more overhead destroy individual threads

Multithreading
Multithreading in Java is a process of executing multiple threads simultaneously.

Advantages of Java Multithreading

1) It doesn't block the user because threads are independent and you can perform multiple
operations at the same time.

2) You can perform many operations together, so it saves time.

3) Threads are independent, so it doesn't affect other threads if an exception occurs in a


single thread.

Multitasking

Multitasking is a process of executing multiple tasks simultaneously. We use multitasking to


utilize the CPU. Multitasking can be achieved in two ways:

o Process-based Multitasking (Multiprocessing)


o Thread-based Multitasking (Multithreading)

1) Process-based Multitasking (Multiprocessing)


o Each process has an address in memory. In other words, each process allocates a
separate memory area.
o A process is heavyweight.
o Cost of communication between the process is high.
o Switching from one process to another requires some time for saving and
loading registers, memory maps, updating lists, etc.

2) Thread-based Multitasking (Multithreading)


o Threads share the same address space.
o A thread is lightweight.
o Cost of communication between the thread is low.

Differences Between Multithreading and Multitasking

Characteristics Multithreading Multitasking


Meaning A process is divided into The execution of more than one
several different sub-processes task simultaneously is called as
called as threads, which has its multitasking.
own path of execution. This
concept is called as
multithreading.
Number of CPU Can be one or more than one One
Number of process Various components of the One by one job is being executed
being executed same process are being at a time.
executed at a time.
Number of users Usually one. More than one
Memory Space Threads are lighter weight. Processes are heavyweight tasks
They share the same address that require their own separate
space address spaces
Communication Inter-thread communication is Inter-process communication is
between units inexpensive expensive and limited.
Context Switching Context switching from one Context switching from one
thread to the next is lower in process to another is also costly.
cost.

Thread Model / Thread Life Cycle (Different states of a Thread)


1. New State
2. Runnable State
3. Running State
4. Waiting/Timed Waiting/Blocked state
5. Terminated State/ dead state

1. New State
 A new thread begins its life cycle in the new state. It remains in this state until the
program starts the thread by calling start () method, which places the thread in the
runnable state.
 A new thread is also referred to as a born thread.
 When the thread is in this state, only start () and stop () methods can be called.
 Calling any other methods causes an IllegalThreadStateException.
 Sample Code: Thread myThread=new Thread();
2. Runnable State:
 After a newly born thread is started, the thread becomes runnable or running by
calling the run () method.
 A thread in this state is considered to be executing its task.
 Sample code: myThread.start();
 The start() method creates the system resources necessary to run the thread
3. Running Thread:
 Thread scheduler selects thread to go from runnable to running state. In running state
Thread starts executing by entering run () method.
 Thread scheduler selects thread from the runnable pool on basis of priority, if priority
of two threads is same, threads are scheduled in unpredictable manner. Thread
scheduler behaviour is completely unpredictable.
4. Waiting/Timed Waiting/Blocked State:
Waiting State:
 Sometimes one thread has to undergo in waiting state because another thread starts
executing. A runnable thread can be moved to a waiting state by calling the wait ()
method.
 A thread transitions back to the runnable state only when another thread signals the
waiting thread to continue executing.
 A call to notify () and notifyAll () may bring the thread from waiting state to runnable
state.

Timed Waiting:
 A runnable thread can enter the timed waiting state for a specified interval of time by
calling the sleep () method.
 After the interval gets over, the thread in waiting state enters into the runnable state.
Sample Code:
try {
Thread.sleep(3*60*1000);// thread sleeps for 3 minutes
}
catch(InterruptedException ex) { }

Blocked State:
When a particular thread issues an I/O request, then operating system moves the
thread to blocked state until the I/O operations gets completed.

Terminated State:
After successful completion of the execution the thread in runnable state enters the
terminated state.
Thread
Synchronization
Definition: Threads Synchronization
 Thread synchronization is the concurrent execution of two or more threads that share
critical resources.
 When two or more threads need to use a shared resource, they need some way to ensure that
the resource will be used by only one thread at a time. The process of ensuring single thread
access to a shared resource at a time is called synchronization.
Why use Synchronization
The synchronization is mainly used to
1. To prevent thread interference.
2. To prevent consistency problem.
Thread Synchronization
There are two types of thread synchronization mutual exclusive and inter-thread
communication.
1. Mutual Exclusive
1. Synchronized method.
2. Synchronized block
2. Cooperation (Inter-thread communication in java)
Java synchronized method
 If you declare any method as synchronized, it is known as synchronized method.
 Synchronized method is used to lock an object for any shared resource.
 When a thread invokes a synchronized method, it automatically acquires the lock for
that object and releases it when the thread completes its task
Syntax to use synchronized method:
Access_modifier synchronized return_type method_name(parameters)
{ …….. }
Example of java synchronized method:
class Table{
synchronized void printTable(int n)//synchronized method
{
for(int i=1;i<=5;i++) {
System.out.println(n*i);
try{ Thread.sleep(400); }
catch(Exception e) { System.out.println(e); }
}
}
}
class MyThread1 extends Thread {
Table t;
MyThread1(Table t){
this.t=t;
}
public void run(){
t.printTable(5);
}
}
class MyThread2 extends Thread{
Table t;
MyThread2(Table t){
this.t=t;
}
public void run(){
t.printTable(100);
}
}
public class TestSynchronization2{
public static void main(String args[]){
Table obj = new Table(); //only one object
MyThread1 t1=new MyThread1(obj);
MyThread2 t2=new MyThread2(obj);
t1.start();
t2.start();
}}

Output
5
10
15
20
25
100
200
300
400
500

2. Synchronized block in java


 Synchronized block can be used to perform synchronization on any specific resource
of the method.
 Suppose you have 50 lines of code in your method, but you want to synchronize only
5 lines, you can use synchronized block.
Points to remember for Synchronized block
 Synchronized block is used to lock an object for any shared resource.
 Scope of synchronized block is smaller than the method.
Syntax to use synchronized block
1. synchronized (object reference expression) {
2. //code block
3. }
Example of synchronized block
class Table{
void printTable(int n)
{
synchronized(this) //synchronized block
{
for(int i=1;i<=5;i++){
System.out.println(n*i);
try{ Thread.sleep(400); }catch(Exception e){System.out.println(e);}
}
}
}//end of the method
}

class MyThread1 extends Thread{


Table t;
MyThread1(Table t){
this.t=t;
}
public void run(){
t.printTable(5);
}
}
class MyThread2 extends Thread{
Table t;
MyThread2(Table t){
this.t=t;
}
public void run(){
t.printTable(100);
}
}

public class TestSynchronizedBlock1


{
public static void main(String args[])
{
Table obj = new Table();//only one object
MyThread1 t1=new MyThread1(obj);
MyThread2 t2=new MyThread2(obj);
t1.start();
t2.start();
}
}
Output:
5
10
15
20
25
100
200
300
400
500

Difference between synchronized method and synchronized block


Synchronized method Synchronized block
 Lock is acquired on whole method  Lock is acquired on critical block of
code only
 Less preferred.  Preferred
 Performance will be less as  Performance will be better as
compared to synchronized block. compared to synchronized method

Inter-Thread Communication
 Inter-Thread Communication or Co-operation is all about allowing synchronized
threads to communicate with each other.
 Definition: Inter-Thread Communication Inter-thread communication is a
mechanism in which a thread is paused running in its critical section and
another thread is allowed to enter (or lock) in the same critical section to be
executed.
 It is implemented by following methods of Object class and all these methods can be
called only from within a synchronized context.
S.No Method and Description
1. public final void wait() throws InterruptedException
Causes the current thread to wait until another thread invokes the notify().
2. public final void wait(long timeout) throws InterruptedException
Causes current thread to wait until either another thread invokes the
notify () method or the notifyAll () method for this object, or a specified
amount of time has elapsed.
Parameters:
timeout − the maximum time to wait in milliseconds.
3. public final void notify()
Wakes up a single thread that is waiting on this object's monitor.
4. Public final void notifyAll()
Wakes up all the threads that called wait( ) on the same object.

Example Program:
class Account
{
double balance = 10000.00;
synchronized public double withdraw( double wamt )
{
System.out.println(" Withdraw process starts ");
System.out.println(" Before Withdraw: "+balance);
if(balance < wamt)
{
System.out.println(" Sorry insufficient balance waiting for deposit ");
try
{
wait(); // if any thread calling wait() then it will release the lock in fraction of seconds and
goes to wait() state life long until notify() method calls
// wait(1000); if you want to wait for some particular amount of time
}
catch( InterruptedException e )
{
e.printStackTrace();
}
}
balance = balance - wamt;
System.out.println(" After Withdraw: " + balance);
return wamt;
}
synchronized public void deposit( double damt )
{
System.out.println("\n\n Deposit process starts: ");
System.out.println(" Before Deposit : "+balance);
balance = balance + damt;
System.out.println(" After Deposit : "+balance);
notify();
// notifyAll(); // if you have multiple threads
}
}
public class Test extends Thread
{
public static void main(String args[]) throws InterruptedException
{
final Account acc = new Account();
new Thread()
{
public void run()
{
acc.withdraw(15000);
}
}.start();

new Thread()
{
public void run()
{
acc.deposit(5000);
}
}.start();
}
}
Output
Creating a Thread
In Java we can implement the thread programs using two approaches -
1. By extending Thread class
2. By implementing Runnable interface.

Thread class:

Thread class provide constructors and methods to create and perform operations on a thread.
Thread class extends Object class and implements Runnable interface.

 The run () method is the most important method in any threading program. By using this
method the thread's behaviour can be implemented. The run method can be written as
follows
Extending Thread Class

 The Thread class can be used to create a thread. Using the extend keyword your class
extends the Thread class for creation of thread. For example if I have a class named A
then it can be written as
class A extends Thread
 Constructor of Thread Class:
o Thread()
o Thread(String s)
o Thread (Runnable obj)
o Thread(Runnable obj, String s);
 Various commonly used methods during thread programming are as given below -

Example Program:
class MyThread extends Thread doin
{
public void run()
{
System.out.println("Thread is created!!!");
}
}
class ThreadProg
{
public static void main(String args[])
{
MyThread t=new MyThread();
t.start();
}
}
Output:

Implementing Runnable Interface

 The thread can also be created using Runnable interface.


 Implementing thread program using Runnable interface is preferable than
implementing it by extending the thread class
class Multi3 implements Runnable{
public void run(){
System.out.println("thread is running...");
}
public static void main(String args[]){
Multi3 m1=new Multi3();
Thread t1 =new Thread(m1); // Using the constructor Thread(Runnable r)
t1.start();
}
}
Output
thread is running...

Multithreading
 Multithreading in Java is a process of executing multiple threads simultaneously.

Advantages of Java Multithreading

1) It doesn't block the user because threads are independent and you can perform multiple
operations at the same time.

2) You can perform many operations together, so it saves time.

3) Threads are independent, so it doesn't affect other threads if an exception occurs in a


single thread.

Example Program:

1. Java Program for creating multiple threads by extending Thread Class


class A extends Thread
{
public void run()
{
for(int i=0;i<=5;i++)//printing 0 to 5
{
System.out.println(i);
}
}
}
class B extends Thread
{
public void run()
{
for(int i=10;i>=5;i--)//printing 10 to 5
{
System.out.println(i);
}
}
}
class ThreadProg
{
public static void main(String args[])
{
A t1=new A();
B t2=new B();
t1.start();
t2.start();
}
}
Output
0
1
2
3
4
5
10
9
8
7
6
5
2. Java Program for creating multiple threads by implementing the Runnable interface
class A implements Runnable
{
public void run()
{
for(int i=0;i<=5;i++)//printing 0 to 5
{
System.out.println(i);
}
}
}
class B implements Runnable
{
public void run()
{
for(int i=10;i>=5;i--)//printing 10 to 5
{
System.out.println(i);
}
}
}
class ThreadProg Runn
{
public static void main(String args[])
{
A obj1=new A();
B obj2=new B();
Thread t1=new Thread(obj1);
Thread t2=new Thread(obj2);
t1.start();
t2.start();
}
}
Output
0
1
2
3
4
5
10
9
8
7
6
5.

Thread Priorities

 Priority of a thread describes how early it gets execution and selected by the thread
scheduler.

 In Java, when we create a thread, always a priority is assigned to it.

 In a Multithreading environment, the processor assigns a priority to a thread scheduler.

 The priority is given by the JVM or by the programmer itself explicitly.


 The range of the priority is between 1 to 10 and there are three constant variables which
are static and used to fetch priority of a Thread. They are as following:

1. public static int MIN_PRIORITY

It holds the minimum priority that can be given to a thread. The value for this is 1.

2. public static int NORM_PRIORITY


It is the default priority that is given to a thread if it is not defined. The value for this is 5.

3. public static int MAX_PRIORITY


It is the maximum priority that can be given to a thread. The value for this is 10.

 There are two commonly used functionalities in thread scheduling


o setPriority
o getPriority
 The function setPriority is used to set the priority to each thread
o Thread_Name.setPriority (priority_val);
 The function getPriority is used to get the priority of the thread.
o Thread_Name.getPriority();

Example using getPriority() method Output


class MyThread extends Thread P1 thread priority : 5
{ Thread Running...
public void run() P2 thread priority : 5
{ P3 thread priority : 5
System.out.println("Thread Running...");
}

public static void main(String[]args)


{
MyThread p1 = new MyThread();
MyThread p2 = new MyThread();
MyThread p3 = new MyThread();
p1.start();
System.out.println("P1 thread priority : " + p1.getPriority());
System.out.println("P2 thread priority : " + p2.getPriority());
System.out.println("P3 thread priority : " + p3.getPriority());
}
}

Example for MAX, MIN and NORM Priority Output


class MyThread extends Thread Thread Running...
{ max thread priority : 10
public void run() min thread priority : 1
{ normal thread priority : 5
System.out.println("Thread Running...");
}
public static void main(String[]args)
{
MyThread p1 = new MyThread();
p1.start();
System.out.println("max thread priority : " + p1.MAX_PRIORITY);
System.out.println("min thread priority : " + p1.MIN_PRIORITY);
System.out.println("normal thread priority : " + p1.NORM_PRIORITY);
}
}

Example : Set Priority Output


class MyThread extends Thread thread priority : 2
{ Thread Running...
public void run()
{
System.out.println("Thread Running...");
}

public static void main(String[]args)


{
MyThread p1 = new MyThread();
// Starting thread
p1.start();
// Setting priority
p1.setPriority(2);
// Getting priority
int p = p1.getPriority();
System.out.println("thread priority : " + p);

}
}

Suspending, Resuming and Stopping Threads


‘• Stopping a thread: A thread can be stopped from running further by issuing the
following statement -

th.stop();

By this statement the thread enters in a dead state. From stopping state a thread can never
return to a runnable state.

‘• Blocking a thread: A thread can be temporarily stopped from running. This is called
blocking or suspending of a thread. Following are the ways by which thread can be blocked

1. sleep()

By sleep method a thread can be blocked for some specific time. When the specified time
gets elapsed then the thread can return to a runnable state.

2. suspend()

By suspend method the thread can be blocked until further request comes. When the resume()
method is invoked then the thread returns to a runnable state.

3. wait()

The thread can be made suspended for some specific conditions. When the notify method is
called then the blocked thread returns to the runnable state.

• The difference between the suspending and stopping thread is that if a thread is
suspended then its execution is stopped temporarily and it can return to a runnable state. But
in case, if a thread is stopped then it goes to a dead state and can never return to runnable
state.
Resuming a thread: The resume() method is only used with suspend() method. This method
is only to resume a thread which was suspended using suspend() method. The syntax is -

public final resume()

Example Program

class MyThread implements Runnable {

Thread thrd;

boolean suspended;

boolean stopped;

MyThread(String name) {

thrd = new Thread(this, name);

suspended = false;

stopped = false;

thrd.start();

public void run() {

try {

for (int i = 1; i < 10; i++) {

System.out.print(".");

Thread.sleep(50);

synchronized (this) {

while (suspended)

wait();
if (stopped)

break;

} catch (InterruptedException exc) {

System.out.println(thrd.getName() + " interrupted.");

System.out.println("\n" + thrd.getName() + " exiting.");

synchronized void stop() {

stopped = true;

suspended = false;

notify();

synchronized void suspend() {

suspended = true;

synchronized void resume() {

suspended = false;

notify();

}
}

public class Main {

public static void main(String args[]) throws Exception {

MyThread mt = new MyThread("MyThread");

Thread.sleep(100);

mt.suspend();

Thread.sleep(100);

mt.resume();

Thread.sleep(100);

mt.suspend();

Thread.sleep(100);

mt.resume();

Thread.sleep(100);

mt.stop();

}
Wrappers
 Wrapper classes are those classes that allow primitive data types to be accessed as
objects.
 The wrapper class is one kind of wrapper around a primitive data type. The wrapper
classes represent the primitive data types in its instance of the class.

• Methods to handle wrapper classes are enlisted in the following table -

int num=obj.intValue();

• Similarly we can use floatValue(), doubleValue() and longValue().


• Similarly in order to convert the numerical value to string the toString() method can be
used. For instance

str=Integer.toString(int_val)

• The variable int_val can be converted to string str.

• For converting the string to numerical value the parseInt or parseLong methods can be used.

Example Program Output


import java.io.*; Creating an object
for value 10
import java.lang.*;
Obtaining the value
class WrapperDemo back from the object:
10
{
The string is: 100
public static void main(String[] args)
Obtaining the
{ numeric value from
the string: 100
System.out.println("Creating an object for value 10");

Integer i=new Integer(10);

System.out.println("Obtaining the value back from the object: "+i.intValue());

String str="100";

System.out.println("The string is: "+str);

System.out.println("Obtaining the numeric value from the string: "+ Integer.parseInt(str));

Autoboxing
Definition: An automatic conversion of primitive data type into equivalent wrapper type is
called as autoboxing.
Example Program
class AutoboxExample
{
public static void main(String args[])
{
//auto-boxing, an int is boxed into Integer object
Integer obj = 111;
//unboxing
int val = obj.byteValue();
System.out.println("Object value = "+obj);
System.out.println("The primitive value = "+val);
}
}
Output

Program for Thread Methods:


class Th extends Thread
{
public void run()
{
Thread t=currentThread();
System.out.println("Thread Status:"+t.isAlive());
for (int i=0;i<=5;i++)
{
try
{
t.sleep(1000);
}
catch(Exception e)
{

}
System.out.println(i);
}
}
}
class TMethods
{
public static void main(String args[])
{
Th t1=new Th();
Th t2=new Th();
/*System.out.println("ID="+t1.getId());
System.out.println("Name of Thread is "+t1.getName());
t1.setName("Balamurugan");
System.out.println("Name of Thread after changing its name "+t1.getName());
System.out.println("Priority of Thread is "+t1.getPriority());
t1.setPriority(10);
System.out.println("Priority of Thread after changing "+t1.getPriority());*/
t1.start();
try{
t1.join();
}
catch(Exception e)
{
}
System.out.println("Thread1 Status:"+t1.isAlive());
t2.start();
}
}

You might also like