Java Unit 3 PPT - Final
Java Unit 3 PPT - Final
Engineering College
24CS202
JAVA PROGRAMMING
UNIT III
• Each process has a separate address in memory and switching from one process to
another requires some time for saving and loading registers and updating lists.
• A process is heavy weight and cost of communication between the process is high.
Thread-based multi-tasking (Multithreading)
• A thread is the smallest unit of a process.
• A process can have multiple threads, each executing different tasks.
• Threads share the same address space.
• A thread is light weight and cost of communication between the thread is
low.
• Executing several tasks simultaneously where each task is a separate
independent part of the same program is called Thread-based multitasking
and each independent part is called Thread.
MULTIPROCESSING
MULTITHREADING
Different between Multitasking and Multithreading
Multithreading
{ { Output:
{ 1
Even t1=new Even(); 3
for(int i=0; i<=20;i=i+2) for(int i=1; i<=19;i=i+2) 5
Odd t2=new Odd(); 7
{ {
Thread ob1=new Thread(t1); 9
[Link](i); [Link](i); 0
Thread ob2=new Thread(t2); 2
} } 4
[Link](); 6
} } 8
[Link](); 10
} } } 12
14
} 11
13
15
17
19
16
18
20
Advantages of Java Multithreading
Runnable
Running
Blocked
Waiting
Timed Waiting
Terminated
THREAD-LIFE CYCLE
Explanation
• New: A newly created thread that has not yet started the execution. It remains
in this state until the program starts the thread using start() method.
• It is also referred to as a born thread.
• Runnable: If a thread is in this state it means that the thread is ready for
execution and waiting for the availability of the processor.
• If all threads in queue are of same priority then they are given time slots for
execution in round robin fashion.
• Running: It means that the processor has given its time to the thread for execution. A
thread keeps running until the following conditions occurs:
(a)Thread give up its control on its own and it can happen in the following situations:
• A thread gets suspended using suspend() method which can only be revived using
resume() method.
• Any thread in these states does not consume any CPU cycle.
• Waiting: A thread waits indefinitely for another thread to perform a task. A thread transitions back
to the runnable state only when another thread signals the waiting thread to continue executing.
• Timed Waiting: A thread that is waiting for another thread to perform a task for a specified
interval of time. A thread in this state transitions back to the runnable state when that time interval
expires or when the event it is waiting for occurs.
• Terminated: A runnable thread enters the dead or terminated state when it successfully completes
its task or otherwise terminated due to any error or even forcefully killed.
The Main() thread
• When we run any java program, the program begins to execute its code starting from the
main method.
• Therefore, the JVM creates a thread to start executing the code present in main method.
This thread is called as main thread.
• A thread can be preempted by a higher priority thread no matter what the lower priority thread is doing.
Whenever a higher priority thread wants to run it does.
Understanding Thread Priority in Java
• Java defines three priority constants in the Thread class:
Get and Set Thread Priority
} OUTPUT EXPLANATION:
•The even thread t1 is started first. It will keep printing even numbers with sleep for 1000 milliseconds for every iteration.
•Since, [Link]() is called, the current thread (which called [Link]()) main thread is paused and waits until t1 completes its execution.
Thread Synchronization
• There are two types of thread synchronization namely mutual exclusive
and inter- thread communication.
• Mutual Exclusive
Synchronized method.
Synchronized block.
Static synchronization.
by synchronized method
by synchronized block
by static synchronization
Synchronized method:
• If you declare any method as synchronized, it is known as synchronized method.
Synchronized method is used to lock an object for any shared resource.
• When a thread invokes a synchronized method, it automatically acquires the lock
for that object and releases it when the thread completes its task.
Example : WITHOUT SYNCHRONIZATION public void run()
class Sample {
{ [Link]();
void show() }
{ }
for(int i=0;i<5;i++) class Test
{ {
[Link]([Link]().getName() + ":" + i); public static void main(String args[])
} {
} Sample s=new Sample();
} MyThread t1=new MyThread(s);
class MyThread extends Thread MyThread t2=new MyThread(s);
{ [Link]();
Sample s; [Link](); OUTPUT
MyThread(Sample s) }
{ }
this.s=s;
}
Example: Synchronized Method public void run()
class Sample {
{ [Link]();
synchronized void show() }
{ }
for(int i=0;i<5;i++) class Test
{ {
[Link]([Link]().getName() + ":" + i); public static void main(String args[])
} {
} Sample s=new Sample();
} MyThread t1=new MyThread(s);
class MyThread extends Thread MyThread t2=new MyThread(s);
{ [Link]();
Sample s; [Link]();
MyThread(Sample s) } OUTPUT
{ }
this.s=s;
}
Synchronized Block
Definition
• Inter-Thread communication or Co-operation is defined as the
process of allowing synchronized threads to communicate with each
other.
Methods of Object class used to implement Inter-Thread
Communication
wait()
notify()
notifyAll()
• wait() Method causes current thread to release the lock and wait until
either another thread invokes the notify() method or the notifyAll()
method for this object, or a specified amount of time has elapsed.
Syntax:
public final void wait()throws InterruptedException
public final void wait(long timeout)throws InterruptedException
• notify() method wakes up a single thread that is waiting on this
object's monitor. If any threads are waiting on this object, one of them
is chosen to be awakened.
Syntax: public final void notify()
notifyAll() wakes up all the threads that called wait() on the same object.
Syntax: public void notifyAll()
Understanding the process of inter-thread
communication
wait() sleep()
The wait() method releases the lock. The sleep() method doesn't release the lock.
It should be notified by notify() or notifyAll() After the specified amount of time, sleep is
methods completed.
Example for Inter-Thread Communication (Producer
Consumer Problem)
• The [Link] package contains all the classes required for input and output operations.
Stream
• A stream can be defined as a sequence of data.
There are two kinds of Streams
• FileInputStream
• FileOutputStream.
Some important Byte Stream Methods
unicode.
[Link]("simple message");
int i=[Link]();//returns ASCII code of 1st character
[Link]((char)i);//will print the character
[Link]("error message");
Reading and Writing Console
Reading Console Input
The preferred method of reading console input is to use a character-oriented
stream.
There are three different ways for reading input from the user in the command
line environment(console).
[Link] BufferedReader Class
[Link] Scanner Class
[Link] Console Class
[Link] Buffered Reader Class
• In Java, console input is accomplished by reading from [Link]. To obtain a
character based stream that is attached to the console, wrap [Link] in a
BufferedReader object.
InputStreamReader(InputStream inputStream)
• Because [Link] refers to an object of type InputStream, it can be used for inputStream.
Putting it all together, the following line of code creates a BufferedReader that is
connected to the keyboard:
Method Description
int read(char[] cbuf, int off, int len) It is used for reading characters into a portion of an
array.
void close() It closes the input stream and releases any of the
import [Link].*;
class Test
{
public static void main(String args[])
{
String s = [Link]();
[Link]("You entered string: "+s);
int a = [Link]();
[Link]("You entered integer: "+a);
float b = [Link]();
[Link]("You entered float: "+b);
}
}
Method Description
console.
Example
class Test
{
public static void main(String[] args) Input Computer
{ Output Computer
// Using Console to input data from user
Console con= [Link]();
String name = [Link]();
[Link](name);
}
}
Writing Console Output
• Console output is most easily accomplished with print() and println() methods. These methods are
defined by the class PrintStream which is the type of object referenced by [Link].
• Even though [Link] is a byte stream, using it for a simple program output is still acceptable.
• Because the PrintStream is an output stream derived from the OutputStream, it also implements
the low-level method write(). Thus, write() can be used to write to the console.
• This method writes the byte specified by byteval. Although byteval is declared as an integer, only
the low-order eight bits are written.
Example
Example 1:
Example 2:
class WriteConsoleOutput
{
public static void main(String arg[])
{
int y;
y=’X’
[Link](y);
}
}
Output:
X
different data types while ensuring type safety and code reusability.
Advantages
• Code Reusability – The same class/method can be used for multiple data types.
• Compile-time Checking – Errors are caught at compile time rather than at runtime
Generic class
• A generic class is a class with one or more type variables.
• Generics means parameterized types. It enables to create classes, interfaces, and methods in which
the type of data upon which they operate is specified as a parameter.
• Class, interface, or method that operates on a parameterized type is called generic, as in generic
class or generic method.
Syntax for declaring a generic class:
class class-name<type-param-list >
{ // …
Syntax for declaring a reference to a generic class:
class-name<type-arg-list > var-name =new class-name<type-arg-list >(cons-arg- list);
}
A Generic Class with One Type Parameter
Example:
{
class GenericClass<T>
{ public static void main(String[] args)
T data;
{
GenericClass(T data) GenericClass<String> ob1 = new GenericClass<String>(“Hari”);
{
[Link] = data; GenericClass<Integer> ob2 = new GenericClass<Integer>(100);
}
void display() [Link]();
{ [Link]();
[Link]("Value =" + data);
} }
}
}
Output:
Value is : Hari
• In Java Generics it is possible to set the restriction on the type that will be allowed to pass to a type-
parameter. This is done with the help of extends keyword when specifying the type parameter.
< T extends Number >
• Here we have taken Number class, it can be any wrapper class name. This specifies that T can be only be replaced
by Number class data itself or any of its subclass.
Example1 : Print an array of different type of numbers (using bounded types in Generic method)
class GenericMethod
{ OUTPUT:
public static <T extends Number> void printarray(T[] arr) Displaying Integers
{ 1
for (T i : arr) 2
{ 3
[Link](i); 4
} Displaying Double numbers
} 11.1
} 22.2
class Test 33.3
{
public static void main(String[] args)
Note:
{
Integer[] arr1 = {1, 2, 3, 4};
When we pass a Character Array or a String Array to
Double[] arr2 = {11.1, 22.2, 33.3};
the printarray() method, it shows compilation error
[Link]("Displaying Integers");
as T is bounded to only the Number datatypes.
[Link](arr1);
[Link]("Displaying Double numbers");
[Link](arr2);
}
}
Example 2: Find the square of a number class Test
(Using bounded types in Generic Class) {
interface GenericInterface<T> {
{ public static void main(String[] args)
T getdata();
} {
GenericClass<String> obj = new GenericClass<>(“Hello");
class GenericClass<T> implements GenericInterface<T>
{ [Link]([Link]());
T data; }
GenericClass(T data)
{ }
[Link] = data;
} Output:
public T getdata() Hello
{
return data;
}
}
Generic Restrictions
return ob;
Although we can’t declare static members that use a type parameter declared by the enclosing class, we can declare static
General Restrictions:
Java Runtime Only Recognizes Raw Types, Not Generic Parameters
• Java's virtual machine does not keep track of generic type information at runtime.
• So, you cannot check if an object is an instance of a generic type using instanceof, and if you try to cast to a
generic type, you will get a warning.