You are on page 1of 113

Unit -II

This work is created by N.Senthil madasamy, Dr. A.Noble Mary Juliet, Dr. M. Senthilkumar and is licensed under a
Creative Commons Attribution-ShareAlike 4.0 International License
Exception
• An exception is a problem that arises during the
execution of a program.
• An exception can occur for many different reasons,
Number
Format including the following: End of file exception.
exception – Access a file beyond its limit
Illegal AccessExcepti
– Convert a alpha numeric string to integer
NullPointer
– try to access variable or method out of scope Exception
– Try to access member of any object, but object is null-
– Try to access array element beyond the limit –
– Try divide a Variable by zero errors- ArrayIndexOutof
bounds
Exception
Arithmetic Exception
What is an Exception?
An exception is an unexpected event that occurs
during runtime and causes normal program flow
to be disrupted.

Some of these exceptions are caused by user


error, others by programmer error, and others by
physical resources that have failed in some
manner.
Categories of Exception
• Checked exceptions: A checked exception is an exception that is
typically a user error or a problem that cannot be foreseen by the
programmer. For example, if a file is to be opened, but the file
cannot be found, an exception occurs. These exceptions
cannot simply be ignored at the time of compilation.

• Runtime exceptions: A runtime exception is an exception that occurs


that probably could have been avoided by the programmer. As
opposed to checked exceptions, runtime exceptions are ignored at
the time of compilation.Invalid input

• Errors: These are not exceptions at all, but problems that arise
beyond the control of the user or the programmer. Errors are
typically ignored in your code because you can rarely do anything
about an error. For example, if a stack overflow occurs, an
error will arise. They are also ignored at the time of compilation.
Exception Handling
The way of handling anomalous situations in a program-run is known
as Exception Handling.
Its advantages are:
 Exception handling separates error-handling code
from normal code
 It clarifies the code and enhances readability
Introduction

 It stimulates consequences as the error-handling


takes place at one place and in one manner
 It makes for clear, robust and fault-tolerant
programs
Concept of Exception Handling

While writing exam


something goes wrong
in your pencil , what
are you doing?
Concept of Exception Handling

Are you stop


and leave the
exam hall?
Concept of Exception Handling

Continue with other


pen?
Are you have
another pen?
Concept of Exception Handling

1 •Write code such that it raises an error flag every time something goes wrong [throw exception]

2 •Error flag is raised, then

3 •Call the Error-handling routine [catch exception]


5 Keywords
• try
– Block that contains the program statements that are monitored.
– Exceptions, if any, are thrown by “try block”
• Catch
– Block that catches the thrown exception and handles it.
– Present immediately after “try”
• Throw
– Used to throw manually generated exceptions (System generated
exceptions are thrown automatically)
• Throws
– Any exception that is thrown out of a method, uses throws clause
• Finally
– Contains a code, that should be executed for any case of
exception
10
Java: Try-Catch Mechanism

try
Wherever the code may trigger an
{
exception, the normal code logic is placed
//Protected code inside a block of code starting with the
} “try” keyword:

catch(ExceptionType1 e1)
After the try block, the code to handle
{
the exception should it arise is placed in a
//Catch block block of code starting with the “catch”
} keyword.

finally
The finally keyword is used to create a
{
block of code that follows a try block. A
//The finally block always finally block of code always executes,
executes. whether or not an exception has
} occurred. protected code.
Exception Types

Super Class

SubClasses of “Throwable”

SubClass of “Exception”

12
Java Exception Hierarchy
class excep
{
public static void main(String arg[])
{ The exception is handled by
int d=0; “default exception handler” of
int a=58/d; JVM
System.out.println("a="+a);
System.out.println("After exception");
}
}

14
Using try and catch
class excep
{
public static void main(String arg[])
{
int d=0;
int a=0;
try
{
a=58/d;
System.out.println("a="+a);
}
catch(ArithmeticException e)
{
System.out.println("Exception!! Divide by zero");
}
System.out.println(“After exception”);
}
}
15
Displaying a Description of an Exception
class excep
{
public static void main(String arg[])
{
int d=0;
int a=0;
try
{
a=58/d;
System.out.println("a="+a);
}
catch(ArithmeticException e)
{
System.out.println("Exception!! “ +e);
}
System.out.println(“After exception”);
}
}
16
Multiple Catch Blocks
Syntax: try
{
//Protected code
}
catch(ExceptionType1 e1)
{
//Catch block
}
catch(ExceptionType2 e2)
{
//Catch block
}
catch(ExceptionType3 e3)
{
//Catch block
}
Syntax Exception Stack

try {
// try1 block generating excep1
try
{
TOS try1 catch
//try2 block generating excep2 Excep2 handler
}
try2 catch
catch (Excep1 ex1) { Excep1 handler
// exception handler for Type1
} try2 block
} generating excep2
catch (Excep2 ex2) { try1 block
// exception handler for Type2 generating excep1
} JVM Default Handler will handle this
18
class excep
{
public static void main(String args[])
{
try
{ int a = args[0];
System.out.println("a = " + a);
int b = 42 / a;
try
{ int c[] = new int[a];
c[42] = 99;
} catch(ArrayIndexOutOfBoundsException e)
{System.out.println("Array Index Exception!!! " + e); }

}catch(ArithmeticException e)
{ System.out.println("Divide By Zero!!!! " + e); }

System.out.println("After try/catch blocks.");


}
}
19
throw
• program to throw an exception explicitly, using the
throw statement.
throw ThrowableInstance;
• ThrowableInstance must be an object of type
Throwable or a subclass of Throwable
• There are two ways you can obtain a Throwable
object
– using a parameter in a catch clause
– creating one with the new operator
20
class excep
{
public static void main(String args[])
{
try
{
if (args.length==0) throw new ArithmeticException();

}
catch(ArithmeticException e)
{
System.out.println("Inside main() catch " + e);
}
System.out.println("After try/catch blocks.");
}
}

21
throws
• Methods that cannot/will not handle the
exceptions thrown, may use “throws” clause
to handle it in some other way.
• Throws clause lists the types of exceptions
that a method might throw
return-type method-name (params) throws Exception-List
{…}
public static void main(String args[]) throws Exception

22
class mythrows
{

void get(int x) throws ArithmeticException, ArrayIndexOutOfBoundsException


{
int a=98/x; // No try and catch blocks here…
int m[]=new int[x];
m[10]=10;
}

public static void main(String args[])


{
try{
mythrows s=new mythrows();
s.get(Integer.parseInt(args[0]));
}
catch( Exception e)
{
System.out.println("Inside main() catch " + e);
}
System.out.println("After try/catch blocks.");
}

23
}
finally
• The finally block will execute whether or not an exception is
thrown, whether or not catch matches
• This can be useful for closing file handles and freeing up any
other resources that might have been allocated at the
beginning of a method
• However, each try statement requires at least one catch or a
finally clause.
• finally => block of code that is executed after a try /catch
block has completed and before the code following the
try/catch block.

24
Finally
public class ExcepTest
{
public static void main(String args[])
{
int a[] = new int[2];
try
{
System.out.println("Access element three :" + a[3]);
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("Exception thrown :" + e);
}
finally
{
a[0] = 6;
System.out.println("First element value: " +a[0]);
System.out.println("The finally statement is executed");
}
}
}
Declaring Your Own Exception

You can create your own exceptions in Java. Keep the following
points in mind when writing your own exception classes:

€ All exceptions must be a child of Throwable.


€ If you want to write a checked exception that is
automatically enforced by the Handle or Declare Rule, you
need to extend the Exception class.
€ If you want to write a runtime exception, you need to
extend the RuntimeException class.
Syntax:
Syntax
class exceptionclassname extends Exception
{

Example

class MyException extends Exception{ }


Syntax:
Example :
Create a student class with following details
Name, Dept_code, Date of joining, Rollno
Format for Dept_code : two char .[eg: EC,CS,CE]

Write a main method to read the above details and


validate the department. If the dept_code not in above
format then raise an exception called
InvalidDept_codeException.
Step 1: Create a Exception class with given name =>
InvalidDept_codeException
class InvalidDept_codeException extends Exception
{

public InvalidDept_codeException(String s)
{
System.out.println("Department Exception : "+s);

}
}
Step 2: Identifying an exception raising situation in this example
Character.isDigit()
1. When user enter more than 2 characters.
Character.isLetter()
2. When user enter digits

Step 3: Write a coding to check these condition and raise


exception
String.charAt(index)
public class student
{
String name, deptartment ,doj,rollno;
public static void main(String args[])
{
student s=new student();

Scanner scan=new Scanner(System.in);

System.out.print("\nEnter Student name :"); s.name=scan.next();

System.out.print("\nEnter Student Dept :");String dept=scan.next();


1
try {
if(dept.length()!=2) 2
throw new InvalidDept_codeException ("Department Length Must be 2.......");

if( (Character.isDigit(dept.charAt(0))) || ( Character.isDigit(dept.charAt(1))))


throw new InvalidDept_codeException ("Department Must be Letter not
Digit ......");

}catch(InvalidDept_codeException e){}
Chained Exceptions
• A feature that allows to associate an exception
with another exception
• The second exception describes the cause of
the first one.
• 2 new methods:
– Throwable getCause()
– Throwable initCause(Throwable CauseExcep)

31
Example
try {

} catch (IOException e)
{
throw new SampleException("Other IOException", e);
}
PACKAGE
• Packages in java are like directories in our
existing file system.
• It contains our class files.
• A java package is a group of similar types of
classes, interfaces and sub-packages.
– built-in package
– user-defined package.
• Advantage of Java Package
– 1) Java package is used to categorize the classes
and interfaces so that they can be easily
maintained.
– 2) Java package provides access protection.
– 3) Java package removes naming collision.
Build-in Package
• There are many built-in packages such as
java, lang, awt, javax, swing, net, io, util, sql
etc.
• These packages consists of a large number
of classes which are a part of Java API.
• For e.g, we have used java.io package
previously which contain classes to support
input / output operations in Java.
• Similarly, there are other packages which
provides different functionality.
Build-in Package
Importing of Packages
• In a Java source file, import statements occur
immediately following the package statement (if it
exists) and before any class definitions.

• This is the general form of the import statement:


• import pkg1 [.pkg2].(classname | *);
• There is no practical limit on the depth of a package
hierarchy, except that imposed by the file system.
Finally, you specify either an explicit classname or a
star (*), which indicates that the Java compiler
should import the entire package.

– import java.util.Date;
– import java.io.*;
• Consider the following statements :
1 ) import java.util.Vector; // import the Vector
class from util package
2 ) import java.util.*; // import all the class from
util package
First statement imports Vector class
from util package which is contained
inside java package.
Second statement imports all the classes from util
package
User defined Package
• Now, we will see how to create packages and use
them.
• Suppose, we want to create a package
named MyPack which contains a class named C1.
• First, we will create a directory named MyPack
( the name should be same as the name of the package ).
• Then create the C1 class with the first statement
being package Mypack;.
• Now, the package is ready to be imported.
Defining a Package
A package is both a naming and a visibility control
mechanism:
1) divides the name space into disjoint subsets.
It is possible to define classes within a package
that are not accessible by code outside the package.
2) controls the visibility of classes and their members.
It is possible to define class members that are only
exposed to other members of the same package.
 Same-package classes may have an intimate knowledge of
each other, but not expose that knowledge to other
packages
Creating a Package
• A package statement inserted as the first line of
the source file:

package myPackage;
class C1 { … }

• means that C1.class file belong to the myPackage


package.
• The package statement creates a name space
where such classes are stored.
• When the package statement is omitted, class
names are put into the default package which has
no name.
Package Hierarchy
• Suppose you wish to create a package hierarchy,
and create a C1.class under the following files
structure ,
• -Mypackage3
– myPackage2
• myPackage3
then,you should write the first statement for
C1.java is
package myPackage1.myPackage2.myPackage3;
• You cannot rename a package without renaming
its directory!
Importing of Packages

• Since classes within packages must be fully-


qualified with their package names, it would
be tedious to always type long dot-separated
names.
• The import statement allows to use classes or
whole packages directly.
• Importing of a concrete class:
import myPackage1.myPackage2.myClass;
• Importing of all classes within a package:
import myPackage1.myPackage2.*;
Package Hierarchy

• Suppose you wish to create a package hierarchy like


F:\MCET

Current
Pack

P1
P2
A.Java
B.Java
C.Java
Test.java A.class B.class C.class
Test.Java
Package P1; import P1.A;
A.Java
public class A
import P1.B;
{
import P2.C;
public void display()
{System.out.println(“I am A in P1”);} public class Test
} {
public static void main(String s[])
Package P1; B.Java
public class B {
{ A aa=new A();
public void display() B bb=new B();
{System.out.println(“I am B in P1”);} C cc=new C();
}
aa.display();
Package P2; bb.display();
public class C C.Java
cc.display();
{
public void display() }}
{System.out.println(“I am C in P2”);} Class , constructor
} and methods should
be public in package
How to compile this example
>javac -d <path> filename.java

>javac –d G:\MCET\Pack A.Java


>javac –d G:\MCET\Pack B.Java
>javac –d G:\MCET\Pack C.Java
>

Now java classes are ready to execute . Suppose you give

javac Test.java

then you got an error. Why did you get error?


Accessing a Package
• As packages are stored in directories, how
does the Java run-time system know where to
look for packages?
• Two ways:
1) The current directory is the default start
point - if packages are stored in the current
directory or sub-directories, they will be
found.
2) Specify a directory path or paths by setting
the CLASSPATH environment variable.
Accessing a Package
• In this example
Set classpath=“ G:\MCET\Pack;%classpath%”

javac Test.java Helps to retain


existing class path
Accessing a Package
• The Test.java program will be modified like
package current;
import P1.A;
We can give file name with package name
import P1.B;
import P2.C; G:\MCET>java current.Test
public class Test
{
public static void main(String s[])
{
A aa=new A();
B bb=new B();
C cc=new C();
aa.display();
bb.display();
cc.display();
}}
}
Access Protection
Interfaces
Interfaces
• Using interface, you can specify what a class
must do, but not how it does it
• Only method declaration, without
implementation
• Similar to class, but
– No instance variables (final)
– Methods without body
• Any number of classes can access (implement)
this interface
Interfaces …
• A class can implement any number of
interfaces.
– Hence achieving multiple inheritance
– Drawback of multiple inheritance?

Class A Class B
void get()
{
SOP(“Should be printed”); void get()
} {
SOP(“Should not be printed”);
Class C }

C cc = new C ();
cc.get();
Syntax
The Declaration of Interface consists of a keyword interface, its name, and the
members.
interface InterfaceName {
// constant declaration
static final type variableName = value;
// method declaration
returntype methodname (argumentlist);
}
The Class that Implements Interface called as Implementation Class uses keyword
implements:
class classname implements InterfaceName {
... }
54
Semantic Rules for Interfaces
• Instantiation
Does not make sense on an interface. Interfaces are not classes. You can
never use the new operator to instantiate an interface.
public interface Comparable {. . . }

Comparable x = new Comparable( );


• Data Type
An interface can be used as a type, like classes. You can declare interface
variables
class Employee implements Comparable {. . . }
Comparable x = new Employee( );

55
Semantic Rules for Interfaces
• Access modifiers

 An interface can be public or default.

 All methods in an interface are by default abstract and public.

- Static, final, private, and protected cannot be used.

 All variables (“constants”) are public ,static, final by default

-Private, protected cannot be used.

• Suppose you declare a method as a public in interface ,then you cant declare that

same method as default.

56
interface inter
{
void display();
int i=10;
}

class sample1 implements inter


{
void display()
{
System.out.println("Hello; inside sam1. Value of i="+i);
}
}

class sample2 implements inter


{
void display()
{
System.out.println("A new method. Inside sam2. Value of i="+i);
}
}
class interdemo
{
public static void main(String args[])
{
sample1 s1=new sample1();
sample2 s2=new sample2();
s1.display();
s2.display();
}
}
interface inter
{
void display();
int i=10;
}

class sample1 implements inter


{
public void display()
{
System.out.println("Hello; inside sam1. Value of i="+i);
}
}

class sample2 implements inter


{
public void display()
{
System.out.println("A new method. Inside sam2. Value of i="+i);
}
}
class interdemo
{
public static void main(String args[])
{
sample1 s1=new sample1();
sample2 s2=new sample2();
s1.display();
s2.display();
}
}
Accessing Implementations Through Interface
References
class interdemo
{
public static void main(String args[])
{
inter inn=new sample1(); Variable “inn” is of type “inter” interface.
inn.display(); But initialized/ assigned with the address of
inn=new sample2(); Class sam1 and sam2
inn.display();
}
}
Accessing Implementations Through Interface
References
class interdemo
{
public static void main(String args[])
{
inter inn=new sam1(); Variable “inn” is initialized with the address
inn.display(); of Class sam1
sam2 ss=new sam2();
inn=ss; Then it is assigned (overwritten) with the
inn.display(); address of Class sam2
}}
Partial Implementations
interface inter
{ class interdemo
void display(); {
void fun(); public static void main(String
} args[])
{
class sam1 implements inter sam1 ss=new sam1();
{ ss.display();
public void display()
{ }
System.out.println("Hello; inside sam1”); }
}
}
Nested Interfaces
• An interface can be declared a member of a
class or another interface
• 2 ways of declarations:
interface <outer_interface> class <class_name>
{ {
Methods… Methods…
interface <inner_interface> interface <interface_name>
{ {
Methods… Methods…
} }

} }
interface outer
{ class interdemo
void display(); {
interface inner public static void main(String
{ args[])
void fun(); {
}
sam1 s1=new sam1();
} s1.display();
class sam1 implements outer sam2 s2=new sam2();
{ s2.fun();
public void display()
{ }
System.out.println("Inside sam1; display"); }
}
}
class sam2 implements outer.inner
{
public void fun()
{
System.out.println("Inside sam2; fun");
}
}
class sam1
class interdemo
{
{
interface inner
public static void main(String
{
args[])
void display();
{
}
sam1 s1=new sam1();
s1.get();
void get()
sam2 s2=new sam2();
{
s2.display();
System.out.println("Inside sam1; get");
}
}
}
}

class sam2 implements sam1.inner


{
public void display()
{
System.out.println("Inside sam2; display");
}
}
Variables in Interfaces
• Variables used in interfaces are by default final
• Used to import shared constants into multiple
classes
Variables in Interfaces
interface vari class ex1
{ {
int x=10; public static void main(String
int y=20; args[])
void get(); {
} A aa=new A();
aa.get();
class A implements vari }
{ }
public void get()
{
x=x+10;
y=y+10;
System.out.println("X="+x+"Y="+y);
}
}
Interfaces Can Be Extended
interface interA
{
void meth1();
}

interface interB extends interA


{
void meth2();
}
class sample implements interB class sample implements interA
{ {
public void meth1() public void meth1()
{ …} { …}
public void meth2() }
{…}
}
Difference b/w Abstract class & Interface
Exercise
1.Create a student class with following details
Name, Dept_code, Date of joining, Rollno.
The rollno must have the format of year-
department-number. [17CS001]. If the roll no
not in above format then raise an exception
called RollnoException.
Package Hierarchy

• Create a package hierarchy shown in the figure.


C:\Software

OS
Test

License
Open source
Test

Mac Ubundo
Stack Implementation
3.Implement “STACK” using interface, class and array.
• Create an interface with 2 method declarations:
– void push(int item);
– int pop();
• Class 1: FixedStack
– Stack size=5
– Items to be pushed and popped: 10,20,30,40,50
• Class2:DynamicStack
– Stack size & items to be pushed and popped – entered by user
Multithreading
Multitasking
Multitasking
Multitasking is a process of executing multiple
tasks simultaneously.

We use multitasking to utilize the CPU.

Multitasking can be achieved by two ways:


• Process-based Multitasking(Multiprocessing)
• Thread-based Multitasking(Multithreading)
Process-based Multitasking
(Multiprocessing)
• Each process have its own address in memory i.e.
each process allocates separate memory area.
• Process is heavyweight.
• Cost of communication between the process is
high.
• Switching from one process to another require
some time for saving and loading registers,
memory maps, updating lists etc.
Thread-based Multitasking
(Multithreading)
• Threads share the same address space.
• Thread is lightweight.
• Cost of communication between the thread is
low.
• Thread is a piece of code that can execute in
concurrence with other threads.
• It is a schedule entity on a processor
Multithreading
What is a thread ?
• A sequential (or single-threaded) program is one that, when
executed, has only one single flow of control.
– i.e., at any time instant, there is at most only one instruction (or
statement or execution point) that is being executed in the
program.
• A multi-threaded program is one that can have multiple flows of
control when executed.
– At some time instance, there may exist multiple instructions or
execution points) that are being executed in the program
– Ex: in a Web browser we may do the following tasks at the same
time:
– 1. scroll a page, 2. download an applet or image,
– 3. play sound, 4 print a page.
• A thread is a single sequential flow of control within a program.
single-threaded vs multithreaded programs

{ A();
{ A(); A1(); A2(); A3(); newThreads {
B1(); B2(); } { A1(); A2(); A3() };
{B1(); B2() }
}
}
Multithreading
Multithreading
• Multithreading in java is a process of executing multiple
threads simultaneously.
• Thread is basically a lightweight sub-process, a smallest unit
of processing.
• Multiprocessing and multithreading, both are used to
achieve multitasking.
• But we use multithreading than multiprocessing because
threads share a common memory area. They don't allocate
separate memory area so saves memory, and context-
switching between the threads takes less time than
process.
• Java Multithreading is mostly used in games, animation etc.
Why do we need threads?
• To enhance parallel processing
• To increase response to the user
• To utilize the idle time of the CPU
• Prioritize your work depending on priority
Example
• Consider a simple web server
• The web server listens for request and serves it
• If the web server was not multithreaded, the
requests processing would be in a queue, thus
increasing the response time and also might hang
the server if there was a bad request.
• By implementing in a multithreaded environment,
the web server can serve multiple request
simultaneously thus improving response time
Advantages of Java Multithreading
1) It doesn't block the
user because threads are
independent and you can
perform multiple operations
at 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
exception occur in a single
thread.
Life cycle of a Thread
• A thread can be in one of the six states. The java thread
states are as follows:
• BLOCKED
• A thread that has suspended execution because it is waiting to acquire
a lock.
• NEW
• A thread that has not begun execution.
• RUNNABLE
• A thread that either is currently executing or will execute when it gains
access to the CPU.
• TERMINATED
• A thread that has completed execution.
Life cycle of a Thread
• TIMED_WAITING
• A thread that has suspended execution for a specified
period of time, such as when it has called sleep( ).
• This state is also entered when a timeout version of wait( )
or join( ) is called.
• WAITING
• A thread that has suspended execution because it is
waiting for some action to occur. For example, it is waiting
because of a call to a non-timeout version of wait( ) or
join( ).
Life cycle of a Thread

Start()

run()
1. sleep(ms)
2. Wait()
1. Suspend()*

1. resume()*
1. Come to running state after
specified time
2. resume()*
1. outof run() 3. notify() & notifyall()
2. stop()*
commonly used methods of Thread class:
• public void run(): is used to perform action for a thread.
• public void start(): starts the execution of the thread.JVM
calls the run() method on the thread.
• public void sleep(long miliseconds): Causes the currently
executing thread to sleep (temporarily cease execution) for
the specified number of milliseconds.
• public int getPriority(): returns the priority of the thread.
• public int setPriority(int priority): changes the priority of the
thread.
– All Java threads have a priority in the range 1-10.
– Top priority is 10, lowest priority is 1.
– Normal priority ie. priority by default is 5.
– Thread.MIN_PRIORITY - minimum thread priority
– Thread.MAX_PRIORITY - maximum thread priority
– Thread.NORM_PRIORITY - maximum thread priority
• commonly used methods of Thread class:
• public String getName(): returns the name of the thread.
• public void setName(String name): changes the name of the
thread.
• public Thread currentThread(): returns the reference of currently
executing thread.
• public int getId(): returns the id of the thread.
• public Thread.State getState(): returns the state of the thread.
• public boolean isAlive(): tests if the thread is alive.
• public void yield(): causes the currently executing thread object
to temporarily pause and allow other threads to execute.
• public void suspend(): is used to suspend the thread(depricated).
• public void resume(): is used to resume the suspended
thread(depricated).
• public void stop(): is used to stop the thread(depricated).
• public boolean isDaemon(): tests if the thread is a daemon
Thread ecology in a java program
started by java from main(String[])

started by main thread

started by B thread

lifetime of C thread
How to create thread
• Each Java Run time thread is encapsulated in
a java.lang.Thread instance.
• Two ways to define a thread:
1. Extend the Thread class
2. Implement the Runnable interface
How to create thread
• Steps for extending the Thread class:
1. Subclass the Thread class;
2. Override the default Thread method run(), which is the
entry point of the thread,
 like the main(String[]) method in a java program.
3. Create a instance of the above thread class
4. Start the thread

• Commonly used Constructors of Thread class:


– Thread()
– Thread(String name)
– Thread(Runnable r)
– Thread(Runnable r,String name)
Java Thread Example by extending Thread class
User Thread name

class Multi extends Thread{ Override run() method


public void run(){
System.out.println("thread is running...");
}
public static void main(String args[]){
Multi t1=new Multi(); Create a instance/object of
thread
t1.start();
} Start the thread

}
Output:t
hread is running...
Create a thread named as phone. When thread starts print “Ring…
Ring” five times
class phone extends Thread{
public void run(){
for(int i=1;i<=5;i++)
{
try
{
Thread.sleep(1000);
System.out.println("Ring ....Ring...");
}catch(Exception e){}
}
}
public static void main(String args[]){
phone t1=new phone();
t1.start();
}
}
Runnable interface:
• The Runnable interface should be implemented by any class
whose instances are intended to be executed by a thread.
Runnable interface have only one method named run().
Runnable interface :
package java.lang;
public interface Runnable { public void run() ; }

Steps using Runnable interface:


1. implement Runnable in to class
2. Write the implementation of run() method
3. Create a instance of class.
4. Create a thread object with runnable object
5. Start the thread.
Java Thread Example by implementing
User Thread name
Runnable interface
class Multi3 implements Runnable{
public void run(){ Implementing run() method
System.out.println("thread is running...");
}
Create a instance/object of
user runnable class
public static void main(String args[]){
Multi3 m1=new Multi3(); Create a thread
instance/object using user
Thread t1 =new Thread(m1); defined runnable object
t1.start();
Start the thread
}
}
Starting a thread

• start() method of Thread class is used to start


a newly created thread. It performs following
tasks:
• A new thread starts(with new callstack).
• The thread moves from New state to the
Runnable state.
• When the thread gets a chance to execute, its
target run() method will run.
Thread Scheduler in Java

• The thread scheduler mainly uses:


– preemptive or time slicing scheduling to schedule the threads.

• Difference between preemptive scheduling and time


slicing
– Under preemptive scheduling, the highest priority task
executes until it enters the waiting or dead states or a higher
priority task comes into existence.

– Under time slicing, a task executes for a predefined slice of


time and then reenters the pool of ready tasks. The scheduler
then determines which task should execute next, based on
priority and other factors.
• Can we start a thread twice?
• No. After starting a thread, it can never be started again. If
you does so, an IllegalThreadStateException is thrown.
• In such case, thread will run once but for second time, it will
throw exception.

• Let's understand it by the example given below:


public class TestThreadTwice1 extends Thread{
public void run(){ System.out.println("running..."); }
public static void main(String args[]){
TestThreadTwice1 t1=new TestThreadTwice1();
t1.start();
t1.start();
}
}
Thread Priorities

• JVM selects to run a Runnable thread with the highest


priority.
• All Java threads have a priority in the range 1-10.
• Top priority is 10, lowest priority is 1.
• Normal priority ie. priority by default is 5.
• Thread.MIN_PRIORITY - minimum thread priority
• Thread.MAX_PRIORITY - maximum thread priority
• Thread.NORM_PRIORITY - maximum thread priority

• Whenever a new Java thread is created it has the same
priority as the thread which created it.
• Thread priority can be changed by the setpriority()
method.
Priority of a Thread (Thread Priority):
class TestMultiPriority1 extends Thread{
public void run(){
System.out.println("running thread name is:"+
Thread.currentThread().getName());
System.out.println("running thread priority is:"+
Thread.currentThread().getPriority());

}
public static void main(String args[]){
TestMultiPriority1 m1=new TestMultiPriority1();
TestMultiPriority1 m2=new TestMultiPriority1();
m1.setPriority(Thread.MIN_PRIORITY);
Output:r
m2.setPriority(Thread.MAX_PRIORITY); Running thread name is:Thread-0
m1.start(); running thread priority is:10
m2.start(); running thread name is:Thread-1
running thread priority is:1
}
Priority of a Thread (Thread Priority):
class TestMultiPriority1 extends Thread{
public void run(){
System.out.println("running thread name is:"+
Thread.currentThread().getName());
System.out.println("running thread priority is:"+
Thread.currentThread().getPriority());

}
public static void main(String args[]){
TestMultiPriority1 m1=new TestMultiPriority1();
TestMultiPriority1 m2=new TestMultiPriority1();
m1.setPriority(10);
Output:r
m2.setPriority(Thread.MAX_PRIORITY); Running thread name is:Thread-0
m1.start(); running thread priority is:10
m2.start(); running thread name is:Thread-1
running thread priority is:1
}
Everyone talking at the same time
Intertwine Conversations
Two Independent Groups
Synchronization
Thread Scheduler in Java

My Thread
run()

MyThread T1 MyThread T2

Synchronization is the mechanism that ensures that only one


thread is accessed the resources at a time
Synchronization
• When two or more threads need access to a
shared resource, they need some way to ensure
that the resource will be used by only one thread
at a time.
• The process by which this is achieved is called
synchronization.
• Java provides unique, language-level support for
it.
• Key to synchronization is the concept of the
monitor.
Synchronization
• A monitor is an object that is used as a
mutually exclusive lock.
• Only one thread can own a monitor at a given
time.
• When a thread acquires a lock, it is said to
have entered the monitor.
• All other threads attempting to enter the
locked monitor will be suspended until the
first thread exits the monitor.
Synchronization
• These other threads are said to be waiting for
the monitor.
• A thread that owns a monitor can reenter the
same monitor if it so desires.
• You can synchronize your code in either of two
ways.
• Both involve the use of the synchronized
keyword, and both are examined here.

You might also like