Professional Documents
Culture Documents
Data Types - Variables and Literals
Data Types - Variables and Literals
LITERALS
Data Types:
• Integral – they can have any numerical value without decimal point.
• Float – Have numerical value with decimal point.
• Char – for storing characters.
• Boolean – for storing true or false.
Variables
Literals
➢ constant values(numbers) used in a program.
➢ there are different types of literals:
• int literals- represen<ng integer type.
• float and double literals- represen<ng decimal type.
• char literals-represen<ng characters in single quotes.
• string literals-represen<ng characters in double quotes.
➢ www.unicode.org
STRING CLASS AND PRINTING
String object:
➢ String is a built-in class available in java.
#1.
➢ str.length(): it returns the length of the string mentioned.
#3.
➢ str.equals(string s): to check whether the contents of two
strings are equal or not.
➢ str.equalsIgnoreCase(string s): to check whether the contents
of two strings are equal or not but it does not depend upon the
case of characters.
➢ str.compareTo(string s): to compare two strings according to
the dictionary order(in accordance with the ASCII codes for
cases of characters).
➢ str.valueOf(int i): to convert different types of data into
string data type.
Regular Expressions:
They are used to define the symbols.
Matching symbols:
➢ these symbols are meant for single alphabets.
➢ ‘.’ it means any letter or the symbol from the keyboard.i.e for
single alphabet it is true.
➢ [abc]: range or set of characters/ the string is true if the
alphabet is either a or b or c.
➢ [abc][vz]: range of multiple symbol/the string is true if first
symbol is among a,b &c and second symbol is among v & z.
➢ [^abc]: the string is true if the symbol is other than a, b, & c.
➢ [a-z 1-7]: the string is true if the symbol is from the range a-z
or 1-7.
➢ A|B: it is true for single alphabets fro either A or b.
Meta characters:
➢ \d: it will be true if it is a digit among 0-9.
➢ \S: it will be true if there are any symbols other than space.
Bitwise operators:
➢ These perform operations on bits of data.
➢ These operations are faster compared to other operators.
➢ Bitwise operators available in java are:
➔ AND &
• result is true if both are true.
➔ OR |
• result is true if any one of the values is true.
➔ NOT ~
• result is inversed.
➔ XOR ^
• result is true if any one of it is true.
➔ Right shift >>
• numbers are shifted to right by one unit and the empty space is
>illed by ‘0’.
➔ Unsigned right shift >>>
• this operator extends the right shift operator.
➔ Left shift <<
• numbers are shifted to left by one unit and the empty space is
>illed by ‘0’.
➢ These operators can be performed on only integer type of data.
class Test
{
Public static void main(string args[])
{
int i=1,n=100;
while(i<n)
{
System.out.println(i);
i=i*2;
}
}
}
}while(condition)
class test
{
public static void main(string args[])
{
int i=1,n=100;
Do
{
System.out.println(i);
i=i*2;
}while(i<n)
For loop:
➢ For loop is a counter controlled loop.
➢ It is the most frequently used loop.
➢ Syntax: for(initialization; condition; updation)
{
------
-------
}
class test
{
public static void main(string args[])
{
for(int i=1;i<=10;i++)
{
System.out.println(i);
}
}
}
Nested loop:
➢ For loop inside a for loop is he example of nested loop.
➢ The above one is used commonly.
➢ The working of the body is more than one dimensional.
➢ Nesting of any two types of loops can be done.
➢ Nested for loop may create the dimensional loops.
Example program for nested for loop
class test
{
public static void main(string args[])
{
for(int i=1;i<5;i++)
{
for(int j=1;j<5;j++)
{
System.out.println(i+”,”+j);
}
}
}
}
ARRAYS
One-Dimensional ARRAY:
➢ Array is a collection of similar data elements.
➢ In java the array size is given after creating the new object.
As int A[]= new int[x];
Where A[] is the reference and int[x] is the object.
Where object is created in the heap.
And the reference is either in stack or heap.
➢ Location of characters in array can be accessed by using their index.
➢ Every array in java has length as its property which can be accessed
by using “array-name.length”.
➢ For loops are most frequently used for arrays.
➢ Using for loop all the elements in the arrays can be accessed/
elements in array can be transveresed using arrays.
➢ Java has introduced for each loop for accessing arrays in version java
1.5 or java 5.
➢ For each loop: syntax for(type var : array)
{
Statements using var;
}
Example program:
class test
{
public static void main(String args[])
{
int A[]={2,4,6,8,10}
for(int i=0;i<A.length;i++)
{
System.out.println(A[i]);
}
for(int i=A.length-1;i>=0;i--)
{
System.out.println(A[i]);
}
}
}
Two-Dimensional ARRAY:
➢ Two-dimensional array are suitable for matrices and tabular form.
➢ Syntax for creating two-dimensional array in java is
: int A[][] = new int [3][4].
➢ It is also known as array of arrays or collection of arrays
➢ Object is created In heap but the reference may or may not be created
in heap.
➢ Array_name.length gives number of rows.
➢ Array_name[index].length gives the number of columns.
Example program:
class test
{
public static void main(String args[])
{
int A[][];
for(int i=0;i<A.length;i++)
{
for(int j=0;j<A[0].length;j++)
{
System.out.println(A[i][j]);
}
System.out.println(“\n”);
}
}
}
➢ In for each loop the array have no integer elements but the reference
elements.
➢ Syntax of for each loop for two dimensional array:
for(type var :array)
{
for(type var1 :type var)
{
Statements using
var(type var 1);
}
}
Example:
class test:
{
public static void main(String args[])
{
int A[];
for(int x[]:A)
{
for(int y:x)
{
System.out.println(y);
}
System.out.println(“\n”);
}
}
}
class test
{
static int max(int x, int y)
{
x++;
if(x>y)
return x;
else
return y;
}
public static void main(String args[])
{
int a=10,b=15,c;
c=max(a,b);
System.out.println(c);
}
}
Passing object as parameters:
➢ To call a method from main method it is needed to be maid static.
➢ When the method is called the value of actual parameters are copied
in formal parameters which is the only parameter passing method in
java.
➢ The address of object in formal and actual parameter is Same.
➢ String cannot be modiIied as it is immutable.
➢ A method can also return an object.
Example program:
class test
{
static void update(int A[])
{
A[0]=25;
}
public static void main(String args[])
{
int A[]={2,3,4,5,6};
update(A);
System.out.println(A[0]);
}
}
class test
{
int add(int x, int y)
{
int z;
z=x+y;
return z;
}
public static void main(String args[])
{
int a=10,b=5,c;
c=add(a,b);
System.out.prinlt(c);
}
}
Method overloading:
➢ Method overloading means writing more than one method having
same names but different parameter list or data types.
➢ Compiler will call the corresponding method depending upon the
parameter list.
Variable arguments:
➢ It is nothing but writing a single method which can run for number of
parameters of same data types.
➢ For example – void show(int …x)
Where … represents the variable arguments.
➢ It is similar to ellipsis in c/c++.
➢ The parameters passed are converted into an array.
➢ The parameters can be directly passed using an anonymous array.
➢ Variable argument should always be the last parameter.
➢ Printf is based on variable arguments in version 1.7 java.
▪ 1.Abstraction
• Abstraction means hiding internal details and showing the required
things.
For Example
Consider a man driving a car, while driving he focus on using of steering, gear,
accelerator etc.
He does not require to know the inner mechanism of the car.
▪ 2.Encapsulation
• Encapsulation is the process of grouping data in a single section.
For Example
Complete television is single box where all the mechanism are hidden inside the
box all are capsuled.
▪ 3.Inheritance
• Inheritance means designing an object or a class by re-using the
properties of the existing class and object.
• Inheritance is same as specialization.
For Example
A old style television (idiot box) is transformed with extra features into slim and
smart television where it re-used the properties of old television.
▪ 4.Polymorphism
• Polymorphism is a concept in which we can execute a single
operation in different ways.
• polymorphism is same as generalization.
➢ Class VS Object
• Object is deEined in terms of its properties and behaviour.
• Operation of behaviours will affect the properties.
• Anything in the world can be deEined in the terms of properties and
behaviour.
• For a single class wee can have many objects.
• Multiple number of objects can be created by one single class
For example
A house or a car or a television is an object but the design or blueprint of the
objeect is a class.
Example Program
class Television
{
private int channel;
private int volume;
➢ Data Hiding
• Usually data is hidden and the operations are made visible and
operations or methods are performed over the data
For example
Actual operation of the television is performed in the circuitry which is done by
pressing a button.so the circuitry is data and operations are methods where the
data is hidden inside the box.
Example Program
class Rectangle
{
public int length;
public int breadth;
➢ Types of Proper:es
• Read and writable property.
• getLength() method will allow us to read the property and
setLength() method will allow us to write the property .
• Read only property.
• When there is no modiEication to the property then read only
property is used.
• Write only property.
• Only set method is used for writing the property where no get
method is used.
➢ Constructors
• A method is required for Initialization of properties at the time of
construction of an object, this method is known as constructor.
• Constructor is a method of class called when an object is created.
• Every class will have a default constructor provided by java compiler.
• Constructor will not have any return type.
• There are two types of constructors
o 1. parameterized
o 2. Non-parameterized.
• Non-parameterized constructors is a replacement for default
constructors.
• Constructors can be overloaded.
INHERITANCE
➢ Generaliza)on VS specializa)on
➢ Generalization
In Generalisation group of classes are referred with Super class with
single name.
Generalisation means Bottom Up.
In Generalisation A Super Class Is made by Grouping Multiple Sub
Classes.
Generalisation is achieved using Interfaces.
For Examples
* Generalization
1.Smart Phone - I phone
Samsung
Vivo
2.Vehicle -Car
Bike
Ship
3.Shape -Triangle
Rectangle
Circle
For Examples
*Specialization
➢ What Is Inheritance?
I Inheritance is the process of acquiring features of an existing Class
into a New Class.
A Class will have Properties and Method.
For Example
A cylinder can acquire all the properties of circle Plus it can have extra
feature
Where we can write a class cylinder inheriting from class circle
A Cuboid can Acquire All the Propertied of A Rectangle Plus Extra feature
Example Program
class Circle
{
private double radius;
public Circle( )
{
radius =0.0;
}
public double area();{}
public double perimeter();{}
};
Circle and Cylinder are the two classes where circle class is having radius
and Cylinder Class acquire the property(radius) of circle with an extra
property that is height.
Cylinder is the Extension of Circle.
extends is the keyword used for Inheritance.
Circle Class Is Parent Class.
Cylinder Class is the Derived Class, Derived Class is also known as
Specialised Class.
In the given example upon the object c1 and c2 the constructors are called
automatically.
In object c1 methods area and perimeter are called
In object c2 methods area.
➢ Constructors in Inheritance
Constructors are the methods of class which are automatically called
when an object is created.
Constructors are executed from Top to Bottom Class.
To make the child class object Pirstly the parent class constructor must be
created
Example Program
class Parent
{
public Parent()
{
System.out.println(“Parent Constructor”);
}
}
class Child extends Parent
{
public Child()
{
System.out.println(“Child Constructor”);
}
}
class Grandchild extends Child
{
public Grandchild()
{
System.out.println(“Grand Child Constructor”);
}
}
class inheritanceDemo
{
Grandchild g=new Grandchild();
}
In the given example Parent Class have its constructor where “parent
constructor” is executed, and Child Class have its constructor where “Child
Constructor”, is executed and Grandchild Class have its constructor where
“Grandchild Constructor” is executed.
In the given example program if a Grandchild class object is created then
as we know Grandchild class inherits Child class constructor and Child class
inherits Parent class constructor so the Grandchild object Pirst executes the
top most class then level by level.
For Example
Car companies manufacture a platform (skeleton of a car)
They will give the shape to a car then first they will create a base which has engines ,seats
etc. and above that they will put a cabin on it so the platform will be same for more of the
cars of that company only the outer body of the cars will be different
Relating to the given program here the platform is the parent class and the base and cabin
created is the child class where the base and cabin is inheriting from the platform
➢ Method Overriding
RedePining the method of the Super Class in the Sub Class.
Method will be called depending on the object.
Method overriding is achieved in Inheritance.
class super
{
public void display()
{
System.out.println(“Hello”);
}
}
class sub extends super
{
public void display()
{
System.out.println(“Hello Welcome”);
}
}
When the sub class object is called then the display method inherited
from the super class is shadowed and the sub class display method is
executed.
Super Class method never be called upon the object of Sub Class.
In the given example program the super class have a method called
display which is saying hello and another class sub class is taken where it
inherits the display method from super class and redePines the method.
When a super class reference holding the object of sub class and
overridden method is called then method of object will be called it is
Dynamic Method Dispatch.
Example Program
class Super
{
Void meth1()
{
System.out.println(“meth1”);
}
Void meth2()
{
System.out.println(“super meth2”);
}
}
class Sub extends Super
{
Void meth2()
{
System.out.println(“sub meth2”);
}
Void meth3()
{
System.out.println(“meth3”);
}
}
class test
{
public.static.void.main()
{
Super s=new Sub();
}
}
Example program
//asuper bstract class
abtract class Super
{
Super()
{
System.out.println(“Super”);
}
void meth1()
{
System.out.println(“meth1”);
}
abstract void meeth2();
}
//concrete class
class sub extends Super
{
Void meth2()
{
System.out.println(“meth2”);
}
}
class test
{
public static void main()
{
Super s1; // reference of abstract is allowed
sub s2 =new sub();
}
}
• Method which is not having a body is known as Abstract method,
the method must be declared as abstract
• The abstract method is unde7ined method
• A class is Abstract class if at least one of the methods is abstract
• If any other class inherits abstract class then that class also becomes
abstract class but to become a concrete class the subclass must
override the unde?ined method
• A class becomes useful if it overrides all the methods of abstract class
• Abstract classes are used for imposing standards and sharing
methods
• Sub classes are meant for following standards
Example Program
class HondaCity
{
static long price=10;
int a,b;
static double OnRoadPrice(String city)
{
Switch(city)
{
Case “Delhi”:
return price+price*0.1;
case “Mumbai”:
return price+preice*0.09;
}
}
}
class test
{
public static void main()
{
• From the given example the “price=10” is the meta data of the class
HondaCity.
➢ Sta$c Blocks
• Set of statements are written in the form of blocks and are made
static.
• It is used to initialise static data member.
• It is executed before the main method at the time of class sloading.
➢ Final Members
• Values of Linal variables are Lixed, once the value is assigned then it
can’t be modiLied.
• Final variables are written in capital letters.
• Final variable can be initialised while declaring the variable, or it can
be initialised in a static block, or else it can be initialised inside
constructor of a class.
• As constructors can be overloaded then the Linal variable must be
initialised in every constructor.
• Final method cannot be overridden.
• A Linal class cannot be extended.
Example Program
class My
{
final int MIN=1;
final int NORMAL;
final int MAX;
static
{
NORMAL=5;
}
My()
{
MAX=10;
}
}
➢ Singleton Class
• A class which can create only one object is called singleton class.
• Constructors are made private to and object of the singleton class is
written in static method.
• In singleton class getInstance() method is used.
Excep&on Handling
➢ What are Excep,ons?
• Exceptions are Runtime Errors.
• There are various types of errors
o Syntax Error
o Logical Error
o Runtime Error.
o
• Syntax Error
• Syntax and Logical errors are faced by Programmers, and runtime
errors are faced by user.
• Spelling or grammatical mistakes are syntax errors, for example
using uninitialised variable it and using unde@ined variable etc and
missing a semicolon etc.
• Syntax errors can be removed with the help of compiler.
• Logical Error
• Logical error is a bug in program that it to operate incorrectly, for
example missing parenthesis in the calculation.
• Logical errors are removed with the help of debugger.
• Runtime Error.
• Mishandling of a program causes Runtime error.
• Causes of runtime errors are bad input, unavailability of resources.
• Major problems with runtime errors is program will crash.
• Exception handling is process of responding to the runtime errors.
➢ How to Handle Excep,ons
• Try and Catch Exceptions
Example program
public class MyClass
{
public static void main(String[] args)
{
try
{
int[] myNumbers = {1, 2, 3};
System.out.println(myNumbers[10]);
}
catch (Exception e)
{
System.out.println(“Something went wrong.”);
}
}
}
• The try statement allows you to de@ine a block of code to be tested for
errors while it is being executed.
• When a try catch block is present in another try block then it is called
a nested try catch block.
➢ Class Excep,on
• Object is the mother class for all the java classes.
• Exception is the parent class for all the exceptions.
• ClassNotFoundException this exception is raised when the object is
used but the class is not found.
• IOException accessing input output, mostly accessing @iles where
@iles are not there or @ile is corrupted one of the famous exception is
the FileNotFoundException.
• InterruptedException it is related to Multithreading if a thread
stops abnormally it throws an Interrupted exception
• NumberFormatException when input is given as a number string
form but not have a proper number, then it throws
NumberFormatException.
• RuntimeExceptions under these there are ArithmeticExceptions,
IndexOutOfBoundException, NullPointerException.
Example program
public class GFG {
public static void main(String[] args)
{
// Use of unchecked Exception
try {
// double x=3/0;
throw new ArithmeticException();
}
catch (ArithmeticException e)
{
e.printStackTrace();
}
}
}
Example program
import java.io.IOException;
• All the things that are outside the program are resource to a program.
• Heap is also a resource to a program.
• Whenever a program needs a resource it should acquire it and when
do not need we should return it.
• To write an object in heap we write new.
• In java heap memory objects are deallocated automatically by
garbage collector.
• Finally keyword is used in association with a try/catch block.
• Finally keyword is meant to execute whether an exception occurs or
not.
• Resources are needed to be closed in @inally block.
• The try-with-resources statement is a try statement that declares one
or more resources.
• The try-with-resources statement ensures that each resource is
closed at the end of the statement.
Example program
static String readFirstLineFromFile(String path) throws
IOException
{
try (BufferedReader br =new BufferedReader(new
FileReader(path)))
{
return br.readLine();
}
}
MULTI-THREADING
WHAT IS MULTI_PROGRAMMING:
➢ Running more than one program that is running multiple programs
on a single machine or a computer is known as multi-programming.
➢ The idea of multiprogramming started from the utilisation of the CPU
when it is idle as the CPU works for just few time in the whole hour.
➢ There are different form of multi-programming.
➔ Multi-user: more than one user using the machine / running their
programs simultaneously.
• for connecting more than one user to single computer the
DUMMY TERMINALS were used.
• here the ROUND ROBIN fashion was introduced as the
programs were executed simultaneously.
• UNIX and LINUX are famous operating systems for the multi-
user environment.
• Multi-user machines were known as TIME_SHARING
machines.
➔ Multi-Tasking: single user runs multiple tasks simultaneously.
• here the CPU runs the programs alternatively on high rate.
• WINDOWS and MacOS(OS X) operating system supports
this type of environment.
➔ MULTI_THREADING: it is a type of multi-threading where there are
different tasks going on under a single application.
• threads are light weighted compared to the task.
• CPU runs the threads alternatively where the user fells the
threads running all together.
• examples: animation, application, gaming, websites,
webserver
CONTROL FLOW OF A PROGRAM
➢ A single program in java contains one control Flow.
➢ Entry point of the program is main method which executes at First.
➢ Example program:
class Test
{
static void display( )
{
s.o.p(“HELLO”);
}
p.s.v main(…)
{
display( );
s.o.p(“WORLD”);
}
}
➢ Example program using runnable interface:
s.o.p(i+“hello”);
i++;
}
}
}
class Test
{
p.s.v main( )
{
My m=new My( );
Thread t=new Thread(m);
t.start( );
int i=1;
while(true)
{
s.o.p(i+”world”);
i++;
}
}
}
Interfaces are implemented.
➢ The class becomes abstract if it does not implements all the features
of interface.
➢ In the above program it gives the example that the object also runs
when the thread runs.
STATES OF A THREAD
➢ The First state of the thread is new it stores the object of the thread.
➢ To run the object of thread the start method is called.
➢ When start method is called then it is entered into the ready state
where it is ready to run.
➢ Then it enters into the running state.
➢ After completing the task it will enter into the terminated state.
➢ A thread which is terminated is just like a thread which is killed.
➢ Therefore the different states of thread are
NEW ! READY ! RUNNING ! TERMINATED
➢ While running the thread may also enter into different states like:
• WAIT STATE: waiting for acquiring some resource or made to
wait by some other thread.
• TIME WAIT STATE: to make the thread to delay for some time
using the sleep method, it is also known as sleep state
• WAIT AND NOTIFY: where the thread is to be in the waiting
state to get to its chance till it gets notiFied.
• BLOCKED STATE: it is just like entering into the monitor where
the thread is being locked for some time, it is similar to waiting
state.
THREAD PRIORITIES
➢ JAVA supports thread priorities from 1-10.
➢ Execution of threads depends upon scheduler.
➢ If a thread is having higher priority then it should get some
preference over other threads.
➢ In java there are different levels of priority that are:
• MIN_PRIORITY=1.
• NORM_PRIORITY=5.
• MAX_PRIORITY=10.
for example:
In MS Word one thread takes the input from the keyboard, another thread
checks for the spellings which works simultaneously, another thread which
works to auto save the document.
In the above the First priority is given to the thread which takes the input
THREAD CLASS
➢ Object of the thread class can be created.
➢ Whenever a thread is created it gets some IDE.
➢ Threads can be identiFied by mentioning their names.
➢ There are different constructors to give the thread classes:
➔ Thread( )
• it is a default class.
➔ Thread(Runnable r)
• the thread contains the runnable interface.
➔ Thread(Runnable r, String name)
• the thread class have its own name with runnable interface.
➔ Thread(ThreadGroup g, String name)
• thread group to manage various threads together.
For example:
Different types of balloons or balls in an animation having their own
thread classes is the example for the thread group.
➔ Thread(String name)
• the thread class have its own name.
For example:
The garbage collector in the JVM which have the least priority.
➢ There are different methods for the enquirying the thread classes:
➔ boolean isAlive( )
• to check if the thread is alive or terminated.
➔ boolean isDaemon( )
• to check if the thread is acting as a daemon or not.
➔ boolean isInterrupted( )
• to check whether the thread is interrupted by some other
methods or not.
SYNCHRONIZATION
➢ DeRinition: it is the coordination or understanding between two
entities.
➢ In multithreading it is usually used between threads.
➢ Terms important to learn synchronization in multithreading:
➔ Resource Sharing:
• it is like more than one thread accessing same resource like
File, network connection, data objects etc
• if there is an object in the heap then it can be accessed by
multiple threads.
• then than object becomes the shared resource.
➔ Critical Section:
• the lines of code in a thread which are accessing the
shared resource/object is the critical section.
• it is said to be a piece of code which is critical.
➔ Mutual Exclusion:
• the mutual exclusion states that the accessing of one
thread prevents the accessing of another.
➔ Locking/Mutex:
• Mutex is the variable used for locking the threads.
• if the mutex variable is set to zero then it is free or it is
not occupied.
• when the time period of one thread is Finished then the
another thread cannot access the object as the mutex will
not remain zero.
• thread two can access the object if and only if the mutex
is zero again.
• for every shared resource there should be a lock which is
being applied by the thread itself.
• here the threads are responsible for mutual exclusion.
• mutex was not useful as the threads would be
overlapping each other if the mutex was not being locked
by the First one.
➔ Semaphore:
• semaphore was like an operating system before the
introducing of java to control the coordination of threads
as they should not overlap.
• it was supported by UNIX operating system.
• the semaphore creates the scenario where the thread
which have been occupying the object would signal the
other after its work is Finished.
• it creates a block queue where the upcoming thread is to
be in waiting state.
• the methods used here are wait( ) and signal( ).
• here the operating system have the mutual exclusion.
➔ Monitor:
• here the object itself takes the responsibility for the
mutual exclusion.
• it can be achieved using object orientation.
• the complete mechanism is inside the object itself.
• the read and write method, the data and the block queue
belongs to the shared object itself as it can be accessed
by any of the threads at a particular time.
• Here java makes sure than one thread is accessed at a
time.
• example program:
class MyData
{
void display (String str)
{
synchronize(this)
{
for(int
i=0;i<str.length();i++)
{
s.o.p(str.charAt(i));
}
}
}
}
class MyThread1 extends Thread
{
Mydata d;
MyThread1(MyData dat){d=dat;}
public void run()
{
d.display(“Hello World”);
}
}
class MyThread2 extends Thread
{
Mydata data;
MyThread2(MyData dat)
{data=dat;}
public void run()
{
d.display(“Welcome”);
}
}
class Test
{
p.s.v.main(…)
{
MyData d=new Mydata( );
Mythread1 t1=new
MyThread1(d);
MyThread2 t2=new
MyThread(d);
t1.start( );
t2.start( );
• the classes Mythread1 and Mythread2 access the data
from the display class which is the shared object.
• the synchronize method is used to execute the classes
separately in the above example.
• synchronize method prints the data separately from both
thread in other words it prevents the data to be
overlapped.
• the for loop inside the synchronize prints one method at
a time.
• The other method for synchronization is to write the
synchronize at the signature method of the display class
so the whole method is being synchronized.
➔ Inter-thread communication:
• it is the communication between the synchronized
threads.
• it is the communication between a single producer
thread and a consumer thread.
• the inter-thread communication refers to the
synchronization between the producer thread and the
consumer thread to access the write and read method
simultaneously.
• to achieve the communication the Flag=t and Flag=f, are
used.
➔ Race condition:
• here there is a single producer thread and multiple
consumer threads.
• here all consumers do not execute at once they do in a
round robin fashion.
• when the count is zero then it is the producers turn.
• and when the count is not zero then it is the consumers
turn.
• since there are more than one consumer any of the
consumer can access it.
• the notify method can open any thread her as they may
not be in an order.
• The race condition states that
• If one thread is accessing the shared resource and
all other are blocked then once the thread has Finished.
• working it will inform the thread and any of the threads
may access the object just like in a race.
• So, in the above the count method is used to control the
race.
• the race condition can be avoided by the inter-thread
condition.
• example program:
class MyData
{
int value=0;
boolean flag=true;
synchronised void set(int v)
{
while(flag!=true)
wait( );
value=v;
flag=false;
notify( );
}
synchronized int get( )
{
int x=0;
while(flag!=false)
wait( )
X=value;
flag=true;
notify;
return x;
}
}