Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
3 views

ITTutor Advanced Java (1)

The document provides a tutorial on advanced programming concepts in Java, focusing on Object-Oriented Programming (OOP) principles such as Abstraction, Encapsulation, Inheritance, and Polymorphism. It explains key concepts with examples, including the differences between abstraction and encapsulation, types of inheritance, and the mechanisms of method overloading and overriding. Additionally, it covers the use of arrays and collections in Java programming.

Uploaded by

Ketema Deba
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

ITTutor Advanced Java (1)

The document provides a tutorial on advanced programming concepts in Java, focusing on Object-Oriented Programming (OOP) principles such as Abstraction, Encapsulation, Inheritance, and Polymorphism. It explains key concepts with examples, including the differences between abstraction and encapsulation, types of inheritance, and the mechanisms of method overloading and overriding. Additionally, it covers the use of arrays and collections in Java programming.

Uploaded by

Ketema Deba
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 87

Department Information Technology

1
Advanced Programming
Tutorial

2
 Tutorial Outlines
 OOP Concepts in java class  Abstraction  Inheritance
Object  Encapsulation  polymorphism

 Array and other collections Array  Array List


List Set

 Exceptions Handling  try….catch  try….catch…finally


throw …. throws
 Multithread in java
 3
OOP Concepts in java
 Class
 Object
 Abstraction
 Encapsulation
 Inheritance

 Polymorphism
4
Abstraction
 It is used to represent the essential feature without representing the back ground details.

 Abstraction focus on what the object does instead of how it does it.

 Abstraction provides us a generalized view of our classes or object by providing relevant


information.
 It is the process of hiding the working style of an object, and showing the information of
an object in understandable manner.
 Abstraction means putting all the variables and methods in a class, which are necessary
for all class members.

5
Abstraction (Cont.…)
 Real world Example of Abstraction: - Suppose we have an object Mobile Phone.

Suppose we have 3 mobile phones as following:-

Nokia 1400 (Features:- Calling, SMS)


Nokia 2700 (Features:- Calling, SMS, FM Radio, MP3, Camera)
Black Berry (Features:-Calling, SMS, FM Radio, MP3, Camera, Video Recording, Reading
E- mails)

Necessary and Common Information) for the object "Mobile Phone" is make
a Call to any number and can send SMS.“

So that, for mobile phone object we will have abstract class like following:

6
Abstraction(Cont....)
abstract class MobilePhone pho ne
M obile
{ o al l
n t
public void Calling(); om mo
//C
public void SendSMS();
}
Public class Nokia1400 extends MobilePhone{
public class Blackberry extends MobilePhone
}
{
Public class Nokia2700 extends MobilePhone
{ public void FMRadio();
public void FMRadio(); Public void MP3();
Public void MP3(); Public void Camera();
Public void Camera(); Public void FMRadio();
} Public void Recording();
Public void ReadAndSendEmails();
}

7
Encapsulation
 It is Wrapping up data member and method together into a single unit (i.e. Class).
 Encapsulation means hiding the internal details of an object, i.e. how an object does
something.

Real world Example


Let's take example of Mobile Phone and Mobile Phone Manufacturer.
Suppose we are a Mobile Phone Manufacturer and we designed and developed a Mobile
Phone design(class),
now by using machinery we are manufacturing a Mobile Phone(object) for selling,
when we sell our Mobile Phone the user only learn how to use the Mobile Phone but not
that how this Mobile Phone works.
8
Difference Between Abstraction and Encapsulation
Abstraction Encapsulation
1. Abstraction solves the problem in the 1. Encapsulation solves the problem
design level. in the implementation level.
2. Abstraction is used for hiding the 2. Encapsulation means hiding the code
unwanted data and giving relevant data. and data into a single unit to protect the data
from outside world.
3. Abstraction lets focus on what the object 3. Encapsulation means hiding the internal
does instead of how it does it details or mechanics of how an object does
something.
4. Abstraction- Outer layout, used in terms 4. Encapsulation- Inner layout, used in
of design. terms of implementation.
For Example:- For Example:- Inner Implementation detail
Outer Look of a Mobile Phone, like it has a of a Mobile Phone, how keypad button and
display screen and keypad buttons to dial a Display Screen are connect with each other
number. using circuits.
9
Inheritance

10
Inheritance

 Inheritance is one of the key features of Object Oriented Programming.

 Inheritance allows a class to inherit property of another class.

 The derived class inherits the states and behaviors from the base class.

 The derived class is also called subclass and the base class is also known as superclass.

 The derived class can add its own additional variables and methods which differentiates the

derived class from the base class.

 When a Class extends another class it inherits all non private data members
Inheritance
 extends and implements keywords are used to describe inheritance in Java.
Inheritance
Inheritance

 If an app is developed using concept of inheritance, it will have following advantages

 Application development time is less.

 Application take less memory.

 Application execution time is less.

 Application performance is enhance (improved).


 Redundancy of the code is reduced ,so that we get consistence results and less
storage cost.
Inheritance

 Types of Inheritance

1. Single Inheritance

2. Multilevel Inheritance

3. Hierarchical Inheritance

4. Multiple Inheritance (Not supported by JAVA class)


Inheritance

1. Single Inheritance:

 When a class extends another one class only, then we call it a single inheritance.
 The flow diagram shows that class B extends only one class which is A.
 Here A is a parent class of B and B would be a child class of A.
Inheritance Single Inheritance example program in Java
Single Inheritance
with final class A
Inheritance
2) Multilevel Inheritance:
 Multilevel inheritance refers to where one can inherit from a derived class,
thereby making this derived class the base class for the other new class.
 As we can see in the diagram below C is derived class or child class of B and
and B is a child class of A.
Example
Multilevel
Inheritance:
Inheritance

3) Hierarchical Inheritance:
 In such kind of inheritance one class is inherited by many sub classes.
 As shown in the flow diagram class B,C and D inherits the same class A.
 A is parent class (or base class) of B, C & D.
Example
Hierarchical
Inheritance:
Inheritance

4) Multiple Inheritance:
 It refers to the concept of one class extending (Inherits) more than one base class.
 The inheritance we learnt earlier had the concept of one base class or parent.
 The problem with “multiple inheritance” is that the derived class will have to
manage the dependency on two base classes.
 Most of the new OO languages like Small Talk, Java, C# do not support
Multiple inheritance.
 Multiple Inheritance is supported in C++
 Why it is not supported by java class ?
Inheritance class A{
void msg( ){
System.out.println("Hello");
}
}
class B{
void msg(){
System.out.println("Welcome");
}
}
class C extends A, B{ //suppose if it were
public static void main(String args[ ]){
C obj=new C( );
obj.msg( );
//Now which msg() method would be invoked ?
}
}
 That is why Java class does not support multiple inheritance.
Inheritance Summary

Class C
Inheritance

But ?

We have noticed that multiple inheritances is not supported in java classes but it’s
supported in interfaces.
A single interface can extend multiple interfaces.

 See an example on next slide


interfaces
 An interface in Java is a blueprint of a class.
 It has static constants and abstract methods.
 The interface in Java is a mechanism to achieve abstraction.
 There can be only abstract methods in the Java interface, not method body.
 It is used to achieve abstraction and multiple inheritance in Java.

interface interface_name{

// Interface body usually abstract methods

}
interface Bank{
abstract float rateOfInterest( );
}
class CBE implements Bank{
public float rateOfInterest( ) { return 7.1f; }
}
class Dashen implements Bank{
public float rateOfInterest( ) {return 7.5f; }
}
class Test{
public static void main(String[] args){
Bank cbe=new CBE ();
System.out.println("ROI: CBE "+ cbe.rateOfInterest( )); // 7.1
Bank dash=new Dashen ();
System.out.println("ROI: DASHEN "+ dash.rateOfInterest( )); //
7.5 }
Inheritance
 The super Keyword
 It is used inside a sub-class method definition to use data variable or to call a method
defined in the immediate parent class object.
 Whenever we create the instance of subclass, an instance of parent class is created
implicitly i.e. referred by super reference variable.
 Private methods of the super-class cannot be called, Only public and protected methods.

 Usage of java super Keyword


1. It is used to differentiate the members of superclass from the members of subclass.
2. It is used to refer immediate parent class instance variable.
3. It is used to invoke immediate parent class constructor.
4. It is used to invoke immediate parent class method
class Automotive {
int speed = 150, produc_year = 2015;
}
class Vehicle extends Automotive {
int speed = 50;
}
class Bike4 extends Vehicle{
int speed =100;
public void display( ){
System.out.println( " The speed is " + super . speed); //will print speed of Vehicle now
}
public static void main (String args[ ]){
Bike4 b = new Bike4( );
b . display( ); Out put :
System.out.println( b. produc_year);
}
The speed is 50
} 2015
Polymorphism

32
Polymorphism

 Polymorphism is the ability of an object to take on many forms.


 It allows us to define one interface and have multiple implementations.
 Polymorphism can be elaborated as:
 An operation may exhibit different behavior in different instances.
 The behavior depends on the types of data used in the operation.
 It plays an important role in allowing objects having different internal structures to share the
same external interface.
 Polymorphism is extensively used in implementing inheritance.
Polymorphism class Fruit {
public void show( ) {
System.out.println("Fruit");
}
}
class Banana extends Fruit {
public void show( ) { //method overridden
System.out.println("Banana");
}
}
public class Application {
public static void main(String[] args) {
Fruit banana = new Banana( );
banana.show( );
Output
}
} Banana
Polymorphism
Types of Polymorphism in JAVA

Method Overloading (Compile-time Polymorphism or Static polymorphism)

Method Overriding (Runtime Polymorphism or Dynamic Polymorphism)


Polymorphism
1. Method Overloading (Compile-time Polymorphism or Static polymorphism)

 In Java, it is possible to define two or more methods of same name in a class,


by provided their argument list or parameters are different.
 This concept is known as Method Overloading.
 Mostly methods should be in the same class.
Argument lists could differ in :
A) Number of parameters.
B) Data type of parameters.
C) Sequence of Data type of parameters
Polymorphism A . Different Number of parameters in argument list
class AA {
public void display( String c ) {
System.out.println(c);
}
public void display( String x, String y ) { //method overloading
System.out.println( x +” ”+y);
}
public static void main(String[] args) {
AA a = new AA( );
a. display( “Single”);
a. display( “First” , ”Second”);
}
}
Polymorphism B . Different in data type of arguments

class AA {
public void display( String c ) {
System.out.println(c);
}
public void display( int x, ) { //method overloading
System.out.println( x);
}
public static void main (String[] args) {
AA a = new AA( );
a. display( “Single”);
a. display( 102);
}
}
Polymorphism C . Different in Sequence of data type of arguments

class AA {
public void display( String name, int id ) {
System.out.println(name + “ , ”+ id);
}
public void display( int id, String name ) { //method overloading
System.out.println( id +” , ”+ name);
}
public static void main (String[] args) {
AA a = new AA( );
a. display( “Alemu” , 1200);
a. display( 1300 , “ Abebe”);
}
}
Polymorphism class AA {
public int display( int x, int y ) {
What will be the output ? return x+y;
}
public float display(int a, int b) {
return a+b;
}
public static void main (String[] args) {
AA a = new AA( );
int k= a. display(100 , 200)
System.out.println( k );
}
}

 Since return type of method doesn’t matter while overloading a method.


Polymorphism

Rules for Method Overloading


1. Overloaded method should always be the part of the same class (can also
take place in sub class), with same name but different parameters.
2. Constructor in Java can be overloaded
3. Overloaded methods must have a different argument list.
4. The parameters may differ in their type or number, or in both.
5. They may have the same or different return types.
Polymorphism
2. Method Overriding (Runtime Polymorphism or Dynamic Polymorphism)

 Declaring a method in subclass which is already present in parent class is


known as method overriding.
 The benefit of overriding is:
 ability to define a behavior that's specific to the subclass type.
 subclass can implement a parent class method based on its requirement.
 In OO terms, overriding means to override the functionality of an existing method.

 For method overriding their must be an inheritance .


Polymorphism class Animal{
public void move( ){
System.out.println("Animals can move");
}
}
class Dog extends Animal{
public void move( ){
System.out.println("Dogs can walk and run");
}
}
public class TestDog{
public static void main (String args[ ] ){
Animal a = new Animal( ); // Animal reference and object
Animal b = new Dog( ); // Animal reference but Dog object
a.move( ); // runs the method in Animal class
b.move( ); //Runs the method in Dog class
}
}
Polymorphism class Animal{
public void move( ){
System.out.println("Animals can move");
}
}
class Dog extends Animal{
public void move( ){
System.out.println("Dogs can walk and run");
}
public void bark( ){
System.out.println("Dogs can bark");
}
This would produce : public static void main (String args[ ] ){
cannot find symbol : Animal a = new Animal( ); // Animal reference and object
method bark() Animal b = new Dog( ); // Animal reference but Dog object
location: class Animal a.move( ); // runs the method in Animal class
b.bark(); b.move( ); //Runs the method in Dog class
^ b. bark( );
}
}
Polymorphism

 Rules for Method Overriding:


1. Applies only to inherited methods
2. Object type (NOT reference variable type) determines which overridden method will be
used at runtime.
3. Overriding method can have different return type (if return types are not primitive) or
user defined return types( object types)
4. Static and final methods cannot be overridden
5. Constructors cannot be overridden
6. It is also known as Runtime polymorphism.
Overriding with
different return type
Array and other collections
Array in java
Arrays are a way to store a list of items.
Each element of the array holds an individual item, and we can place items into and
remove items from those slots as we need to.
Arrays can contain any type of value (base types or objects), but we can’t store different
types in a single array.
We can have an array of integers, or an array of strings, or array of characters
but we can’t have an array that contains, for example, both strings and integers.
 To create an array in Java, we use three steps:
1. Declare a variable to hold the array.
2. Create a new array object and assign it to the array variable.
3. Store things in that array.

Eg String name[ ]; or String [ ] name ;


int numbers[ ]; or int[ ] numbers; 48
Creating Array Objects
The second step is to create an array object and assign it to that variable. There are two
ways to do this:
• Using new
• Directly initializing the contents of that array

The first way is to use the new operator to create a new instance of an array:
 String[] names = new String[3];
 int numbers[]=new int[5];
The second way to create array by initializing the array contents
 String names[]={“Alemu”,”Chala”,”Aster”};

 int numbers[]={21,12,30,40,80};
49
ArrayList
The Java API provides several predefined data structures, called collections, used to store
groups of related objects.
 These classes provide efficient methods that organize, store and retrieve your data without
requiring knowledge of how the data is being stored.
This reduces application-development time.
You’ve used arrays to store sequences of objects.
Arrays do not automatically change their size at execution time to accommodate additional
elements.
The collection class ArrayList<T> (from package java.util) provides a convenient
solution to this problem
it can dynamically change its size to accommodate more elements.
The T (by convention) is a placeholder
50
ArrayList (Cont…)

when declaring a new ArrayList, replace it with the type of elements that you want the
ArrayList to hold.
This is similar to specifying the type when declaring an array, except that only non primitive
types can be used with these collection classes.
For example, ArrayList< String > list; declares list as an ArrayList collection that can
store only String s.
Classes with this kind of placeholder that can be used with any type are called generic
classes.
// to create a new ArrayList of Strings with an initial capacity of 10
ArrayList< String > items = new ArrayList< String >();
51
Some methods and properties of class ArrayList<T>.

52
List
 The java.util package provides the List interface for maintaining the ordered collection.
 A List can contain the null and duplicate values.
 The methods of the List are based on the index, so all the operations like insert, delete,
update, and search is based on the index.
 ArrayList, LinkedList, Stack, and Vector are the implementation classes available in the
List interface.
 In Java, we mostly used the ArrayList and LinkedList implementation classes to design a
list.

53
List Example
1.import java.util.*;
2.class ListExample{
3. public static void main(String args[]){
4. //Create List
5. List<String> names = new ArrayList<String>();

6. //Adding elements in the List.


7. names.add(“Abebe");
8. names.add(“Alemu");
9. names.add(“Chala");
10. names.add(“Abdi");
11. //
Performing iteration of list to print each element of it.

12. for(String name: names)


54
13. System.out.println(name);
Set
 The set is an interface available in the java.util package.
 The set interface extends the Collection interface.
 An unordered collection or list in which duplicates are not allowed is referred to as
a collection interface.
 The set interface is used to create the mathematical set.
 The set interface use collection interface's methods to avoid the insertion of the same
elements.
 SortedSet and NavigableSet are two interfaces that extend the set implementation.

55
Set Example

1.import java.util.*;
2.public class SetExample{
3. public static void main(String[] args)
4. {
5. // creating HashSet implementation using the Set
6. Set<String> veg = new HashSet<String>();
7. veg.add("Ginger");
8. veg.add("Garlic");
9. veg.add("Onion");
10. veg.add("Ginger");
11. System.out.println(veg);
12. }
13.}
OUTPUT
[ Ginger , Garlic,
56
Onion ]
Exceptions Handling

57
Exceptions Handling

 Exception (exceptional event) is a problem happens during the execution of a program.

 When an Exception occurs the normal flow of the program is disrupted and
application terminates abnormally, so exceptions are to be handled.
 The exception handling in java is a mechanism to handle the runtime errors
so that normal flow of the application can be maintained.
 An exception can occur for many different reasons:
 A user has entered invalid data.
 A file that needs to be opened cannot be found.
 A network connection has been lost in the middle of communications or the
 JVM has run out of memory. 58
Let's take a scenario:
•statement 1;
•statement 2; //exception occurs
•statement 3;
•statement 4;

Suppose there is 4 statements in our program and there occurs an exception at statement 2,
rest of the code will not be executed i.e. statement 3 & 4 will not run.
If we perform exception handling, rest of the statement will be executed.

59
public class C{
public static void main(String args[]){
int data=50/0; //may throw exception
System.out.println("rest of the code...");
}
}

Output:
Exception in thread main java.lang.ArithmeticException:/ by zero

60
 Exception Hierarchy

61
 Three categories of Exceptions
 Checked exceptions (Compile time Exception :
A checked exception is an exception that occurs at the compile time, these are also called
as compile time exceptions. E.g FileReader class to read data from a file, if file not found
then an FileNotFoundException occurs.
 Unchecked exceptions (Runtime Exception)
An Unchecked exception is an exception that occurs at the time of execution, these are also
called as Runtime Exceptions. these include programming bugs, such as logic errors or
improper use of an API. ArrayIndexOutOfBoundsException
 Errors
 These are not exceptions at all, but problems that arise beyond the control of the user.
 For example, if a stack overflow occurs, 62
Checked exceptions

Exception Description
ClassNotFoundException Class not found.
CloneNotSupportedException Attempt to clone an object that does not implement the
Cloneable interface.

IllegalAccessException Access to a class is denied.


InstantiationException Attempt to create an object of an abstract class or interface.
InterruptedException One thread has been interrupted by another thread.
NoSuchFieldException A requested field does not exist.
NoSuchMethodException A requested method does not exist.

63
Unchecked exceptions

Exception Description
ArithmeticException Arithmetic error, such as divide-by-zero.
ArrayIndexOutOfBoundsException Array index is out-of-bounds.
ArrayStoreException Assignment to an array element of an incompatible type.
IllegalStateException Environment or application is in incorrect state.
IndexOutOfBoundsException Some type of index is out-of-bounds.
NegativeArraySizeException Array created with a negative size.
NullPointerException Invalid use of a null reference.
NumberFormatException Invalid conversion of a string to a numeric format.
StringIndexOutOfBounds Attempt to index outside the bounds of a string.
64
 Handling Exceptions by using
 try…… catch block
 try…. catch …..finally block
 throws for declaring the exception class
 throw methods used to catch the exception

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

This would produce the following result:


Exception thrown :java.lang.ArrayIndexOutOfBoundsException: 3 First element value: 6
The finally statement is executed
66
Note the following:
 A catch clause cannot exist without a try statement.
 It is not compulsory to have finally clauses whenever a try/catch block is present.
 The try block cannot be present without either catch clause or finally clause.
 Any code cannot be present in between the try, catch, finally blocks.
 For each try block there can be zero or more catch blocks, but only one finally block.
 If you don't handle exception, before terminating the program, JVM executes finally
block(if any).
 The finally block will not be executed if program exits (either by calling System.exit() or
by causing a fatal error that causes the process to abort).

67
Throws example
class ThrowsExecp {
static void fun() throws IllegalAccessException {
System.out.println("Inside fun(). ");
throw new IllegalAccessException("demo");
}
public static void main(String args[]) {
try {
fun();
}
catch(IllegalAccessException e) {
System.out.println("caught in main.");
}
}
} 68
Multithread in java

69
 Multithread in java
OS on single-processor computers create the illusion of concurrent execution by rapidly
switching between activities, but only a single instruction can execute at once.

In the classic programming model, there is a single CPU that reads instructions from
memory and carries them out, one after the other.

This is the only type of programming that we have considered so far ,and has limitations.

Modern computers have multiple processors, enables to perform several tasks at the same time.

To use the full potential of all those processors, we need to write programs that can do
parallel processing . These programs are threads.

In Java, a single task is called a thread which refers to a “thread of control” or “thread
of execution,” meaning a sequence of instructions that are executed one after another.70
 Multithread in java
 Concurrency Vs Parallelism

 Concurrency is about executing/managing multiple instruction/tasks sequences at the


same time on a single CPU.
 parallelism is running/managing multiple instruction sequences at the same time on
multiple CPUs.

(a) multiple threads running on three CPUs (b) multiple threads share a single CPU
71
 What is Multitasking?
 Multitasking is a process of executing multiple tasks simultaneously to utilize the CPU.
 Multitasking can be achieved in two ways:
 Process-based Multitasking (Multiprocessing)
 Each process has an address in memory (process allocated in a separate memory area).
 A process is heavyweight and switching from one process to another requires time for
saving ,loading & registers
 Thread-based Multitasking (Multithreading)

 Threads share the same address space (memory).


 A thread is a light-weight and smallest part of a process that can run concurrently with
the other parts (threads) of the same process
 The process of executing multiple threads simultaneously is known as multithreading.
72
 Multithread in java
Threads are independent. If there occurs exception in one thread, it does not affect other
threads.

73
 Multithread in java
Advantages of Java Multithreading
 It improves concurrency and application responsiveness It improves program structure.
 no need to wait for one thread to complete to start another.
 Multiple threads share the same address and memory space or files simultaneously,
resources is reduced
Limitations of Java Multithreading
 Writing code for multithreaded applications is challenging.
 Their results cannot be easily predicted.
 Finding the root cause of an error and debugging it becomes complex
 Inefficient management of Concurrency and Parallelism may cause problems in the
application.
74
 Multithread in java
 Thread Life Cycle

A thread goes through various stages in its life cycle. For example, a thread is born, started, runs, and then dies. The
following diagram shows the complete life cycle of a thread.

75
 Multithread in java

The various stages of life cycle of thread are


 New/born thread. − it begins its life cycle in the new state until the program starts the thread.

 Runnable − After a newly born thread is started, the thread becomes runnable

 Running A runnable thread in this state is directly transit to running state (executing ).

 Waiting/Blocked: The state when a thread has to wait. E.g.. for synchronization
Waiting can be Timed Waiting state for a specified interval of time.
 Terminated (Dead) − A thread reaches the termination state because of the following
reasons
 When a thread has finished its job, then it exists or terminates normally.

 Abnormal termination: It occurs when some unusual events/ faults76occur.


 Multithread in java
 How to create a thread in Java?
There are commonly two ways to create a thread:
1. By extending Thread class
class A extends Thread{

}
2. By implementing Runnable, interface.

class A implements Runnable{

}
77
 Multithread in java
1. Creating thread using Thread class:
Thread is a java class, which
implements runnable interface

run() is a method for runnable


interface

t1 is a an object of Thread1 (user


defined class) can inherit Thread
properties

start() is a method for Thread


class which calls run( ) method
78
 Multithread in java
1. Creating a Thread by implementing Runnable interface Runna
bl
implem e is a jav
ented b a inte
y Thr rf
ead2 c ace
lass

mt a object for Thread2


class

t1 is Object for Java Thread


And instantiated by Thread2 object
mt as runnable object

t1 then call
s the start(
method agai ) method a
n calls run( nd start
interface ) method of ru
nnable
79
 Multithread in java
 Commonly used methods of Thread class:
1. public void run(): is used to perform action for a thread.
2. public void start(): starts the execution of the thread. JVM calls the run() method
3. public void sleep(long miliseconds): Causes the currently executing thread to sleep
4. public void join(): waits for a thread to die.
5. public int getPriority(): returns the priority of the thread.
6. public int setPriority(int priority): changes the priority of the thread.
7. public boolean isAlive(): tests if the thread is alive.
8. public void yield(): causes the currently executing thread object to temporarily pause
9. public void suspend(): is used to suspend the thread.
10.public void resume(): is used to resume the suspended thread.
11.public void stop(): is used to stop the thread.
12.public void interrupt(): interrupts the thread.
80
 Multithread in java
 Thread Synchronization

• When multiple threads share an object and that object is modified by one or more of the

threads, indeterminate results may occur.

• If one thread is in the process of updating a shared object and another thread also tries

to update it, it is unclear which thread’s update takes effect.

• Synchronization process of handling situations when two or more threads need access

to a shared resource
81
 Multithread in java
 Thread Synchronization…

• The problem can be solved by giving only one thread at a time exclusive access to code that
manipulates the shared object.

• When the thread with exclusive access to the object finishes manipulating it, one of the
waiting threads is allowed to proceed.

• This process, called thread synchronization, coordinates access to shared data by multiple
concurrent threads.

• Ensures that each thread accessing a shared object excludes all other threads from doing
so simultaneously—this is called mutual exclusion.
82
Thread without synchronization method

When t1 and t2 are executed the increament


method, they are not informed on from the other,
e.g 1 is missed, and 2 is written twice. They
share the same method and they are in race
condition (one cannot wait until the other
finishes.

83
Thread with synchronization method

This method makes the thread to wait until


the resource is released by the other thread.

84
 Multithread in java
Thread Priority
 Each thread has a priority.
 Priorities are represented by a number between 1 and 10.
 In most cases, the thread scheduler schedules the threads according to their priority (known
as preemptive scheduling).
int getPriority(): method returns the priority of the given thread.
void setPriority(int priority): method updates or assign the priority of the thread to priority.
3 constants defined in Thread class:
1. public static int MIN_PRIORITY  value is 1
2. public static int NORM_PRIORITY  value is 5 (default)
3. public static int MAX_PRIORITY  value is 10 85
public class Demo extends Thread{
public void run(){
System.out.println("Now, inside the run method"); }
public static void main(String[]args){
Demo my_thr_1 = new Demo();
Demo my_thr_2 = new Demo();
System.out.println("The thread priority of first thread is : " + my_thr_1.getPriority());
System.out.println("The thread priority of first thread is : " + my_thr_2.getPriority());
my_thr_1.setPriority(5); my_thr_2. setPriority(3);
System.out.println("The thread priority of first thread is : " + my_thr_1.getPriority());
System.out.println("The thread priority of first thread is : " + my_thr_2.getPriority());
System.out.print(Thread.currentThread().getName());
System.out.println("The thread priority of main thread is : " + Thread.currentThread().getPriority());
Thread.currentThread().setPriority(10);
System.out.println("The thread priority of main thread is : " +
Thread.currentThread().getPriority());
}
} 86
d”
E n

!
o u
k Y
a n
T h
87

You might also like