0% found this document useful (0 votes)
12 views

Unit-5 Multithreading in Java

The document covers I/O programming in Java, detailing byte and character stream classes, random access files, and multithreading concepts including thread life cycle, methods, and synchronization. It explains exception handling, including types of exceptions and the use of try-catch-finally blocks. Additionally, it provides examples of implementing multithreading using the Runnable interface and demonstrates exception handling through code snippets.

Uploaded by

examsgfgcwt
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views

Unit-5 Multithreading in Java

The document covers I/O programming in Java, detailing byte and character stream classes, random access files, and multithreading concepts including thread life cycle, methods, and synchronization. It explains exception handling, including types of exceptions and the use of try-catch-finally blocks. Additionally, it provides examples of implementing multithreading using the Runnable interface and demonstrates exception handling through code snippets.

Uploaded by

examsgfgcwt
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 9

OOPs Concepts and Programming in Java – NEP 1

UNIT – 5
I/O Programming
Syllabus: Text and Binary I/O, Binary I/O classes, Object I/O, Random Access Files. Multithreading in java:
Thread life cycle and methods, Runnable interface, Thread synchronization, Exception handling with try
catchfinally.

Stream: Stream is a flow of information from a source to a destination.


Ex:- a) A keyboard to a monitor.
b) A monitor to a file on a hard disk.
c) A file on a hard disk to a monitor.

Streams are mainly used to move data from one place to another. The java.io package
contains a large number of stream classes that provide capabilities processing all type of
data.

Streams are basically divided into 2 categories:


1. Byte stream classes (Binary Stream)
2. Character stream classes (Text Stream)

1. Byte stream classes:


To read and write 8-bytes, programs should we the byte streams. The byte streams are
defined by using two classes hierarchies.
Input stream class
Output stream class

2. Character stream classes:


To read and write 16-bytes, programs should we the character streams. The character
streams are defined by using two classes hierarchies.
Reader classes
Writer classes

I BSc, III sem Dept of Computer


Science, GFGC, Tiptur
OOPs Concepts and Programming in Java – NEP 2

BYTE STREAM CLASS

1. Input stream:
Input stream is an abstract class that provides the framework from which all other
input stream is derived.

2. Output stream:
Output Stream is an abstract class that provides the framework from all output stream
is derived.

CHARACTER STREAM CLASS


1. Reader:
Reader is an abstract class that provides the framework from which all other reader
streams are derived.

I BSc, III sem Dept of Computer


Science, GFGC, Tiptur
OOPs Concepts and Programming in Java – NEP 3

2. Writer:
Writer is an abstract class that provides that framework from which all other writer
stream are derived.

Java – Random Access Files


This class is used for reading and writing to random access file. A random access file behaves
like a large array of bytes. There is a cursor implied to the array called file pointer, by moving
the cursor we do the read write operations. If end-of-file is reached before the desired number of
byte has been read than EOFException is thrown. It is a type of IOException.

Constructor
Constructor Description

RandomAccessFile(File Creates a random access file stream to read from, and


file, String mode) optionally to write to, the file specified by the File
argument.

RandomAccessFile(String name, Creates a random access file stream to read from, and
String mode) optionally to write to, a file with the specified name.

I BSc, III sem Dept of Computer


Science, GFGC, Tiptur
OOPs Concepts and Programming in Java – NEP 4

Multithreading in java:
THREAD LIFE CYCLE AND METHODS

Thread: A thread is a lightweight sub-process, the smallest unit of processing.


Multithreading: The process of executing multiple threads simultaneously is called
multithreading.

Life cycle of a Thread:

1. Newborn state: In this state, a new thread begins its life cycle. It involves the
creation of the object of the thread class.
2. Runnable state: A thread, that is ready to run is then moved to the runnable
state. After invocation of start() method the thread becomes runnable.
3. Running state: In this state, the thread is currently being executed by the CPU.
4. Blocked state: In this state, the thread is kept idle/blocked. A thread can be
blocked using suspend, sleep or wait, in order to continue other threads execution.
5. Dead state: a thread enters to dead state, when a thread completes its execution
or by calling a method stop. A thread can be killed in any state.

Methods of Thread class:


1. Start():- It calls the run method to being executing the Thread.
2. Stop():- To kill the Thread.
3. run():- It executes the body of the thread.
4. sleep():- It is used to move a Thread to sleep for a specified amount of a time in mile
second.

I BSc, III sem Dept of Computer


Science, GFGC, Tiptur
OOPs Concepts and Programming in Java – NEP 5

5. wait():- Waiting stage of Thread until the condition.


6. Notify():- After the condition the waiting Thread automatically execute.
7. Resume():- Resumes the execution of the Thread.
8. Suspend():- It is similar to wait when using suspend the method resume will be taken.
9. Yield():- It is used to stop the execution of a particular Thread
10. setName():- It sets the name of a Thread
11. getName():- It returns the name of a Thread
12. Current Thread():- It returns the name of the currently executing the Thread.

RUNNABLE INTERFACE
A thread can be created using two ways:
1. By extending Thread class.
2. By implementing runnable interface

Runnable interface:
Define a class that implements runnable interface. The runnable interface as only one
method run. This can be implemented in our class.
Syntax: interface runnable
{
public void run();
}

Note: We can write the code for the run method in our class.

Example program:
import java.io.*;
import java.lang.*;
class A implements runnable
{
public void run()
{
for (int i=1;i<=5; i++)
System.out.println (“Thread A:”+i);
System.out.println (“exit from A”);
}
}

class B implements runnable


{
public void run()
{
for(int i=1;i<=5; i++)
System.out.println (“Thread B:”+i);
System.out.println (“exit from B”);

I BSc, III sem Dept of Computer


Science, GFGC, Tiptur
OOPs Concepts and Programming in Java – NEP 6

}
}
public class Ex
{
public static void main(String args[ ])
{
A obj1=new A();
B obj2=new B();
Thread t1=new Thread (obj1);
Thread t2=new Thread(obj2);
t1 .start();
t2.start();
}
}

SYNCHRONIZATION
It is the process of avoiding multiple Thread to act on same data or method is called
synchronization.
Synchronization is uses while execution time, the one Thread is under execution process
there is no possibility to enter another Thread into execution.
The synchronization can be achieved in java by two ways
1. By using synchronized method
2. Synchronized block

By using synchronized method:-


The synchronized is used to synchronize the hole method.
Syntax:- Synchronized void withdrawal()
{
………
………
………
}

Synchronize block :-
Synchronized block is used to synchronize block of statement in a method.
Syntax:- Synchronized(object)
{
……..
……..
……..
}

EXCEPTION HANDLING
Error: An error describes any issue that arises unexpectedly that cause a computer to
not function properly.
Basically, errors are classified into 2 types.
1. Compile time errors.

I BSc, III sem Dept of Computer


Science, GFGC, Tiptur
OOPs Concepts and Programming in Java – NEP 7

2. Run time errors.

1. Compile Time Errors.


These errors are syntactical errors, found at the time of compilation by the
compiler.
Ex: missing semicolon, missing flower bracket, missing quotes etc..
2. Run Time Errors.
A runtime error is an error that occurs while the program is running after being
successfully compiled.
Ex: Divide by zero (1/0), Accessing an element out of bounds of an array.

Exception: An error occurs at runtime is called an Exception.

Exception Handling: The mechanism of handling runtime errors or exceptions is called


Exception handling.

Types of Exception:
1. Checked Exceptions: The exceptions, which are listed and checked by the java
compiler during compilation.
Ex: ClassNotFoundException, NoSuchMethodException etc..

2. Unchecked Exceptions: These are exceptions, which are not listed and are
identified during runtime.
Ex: ArithmeticException, NullPointerException etc..

Java exception handling is handled using five keywords:


1. try: This block contains the statements, which causes the exception.
2. catch: This block contains the statements, which handles the exception thrown.
3. throw: This keyword is used when we want to throw exception manually.
4. throws: This keyword used when we want to specify the exception thrown by a
method during the execution of the code.
5. finally: This block contains the statements, which has to be executed after the
exception had occurred.
The finally block is always executed no matter whether there is an exception or not.

Using try and catch


try:
The try block consists of an executable statement that can possible to throw exceptions
implicitly. The try block throw the exceptions implicitly, if the exception occurs in this
block.

catch:
catch block catches the exception thrown by the try block. A catch block consists of the
keyword catch followed by a single parameter that identify the type of exception and ‘e’ is
the object for the class Exception.

I BSc, III sem Dept of Computer


Science, GFGC, Tiptur
OOPs Concepts and Programming in Java – NEP 8

Try block monitors the code, which causes the exception. Immediately following the try
block there must be a catch block which specifies exception type that you want to catch
and handle the exception.

try
{
//statements causing exception
}

catch
{
//statements handling exception
thrown
}

Java program to demonstrate try and catch block:

import java.io.*;
class demo
{
public static void main(String[] args)
{
int d, a;
try
{
d=0;
a=40/d;
System.out.println(“not printed”);
}
catch(ArithmeticException e)
{
System.out.println(“divide by zero error”);
}
}
}

Output:
Divide by zero error

I BSc, III sem Dept of Computer


Science, GFGC, Tiptur
OOPs Concepts and Programming in Java – NEP 9

finally:
finally keyword is used for a block of code that will be executed after try/catch block is
executed. Finally block will be executed whether or not the exception is thrown.
This can be useful for closing the file handles and freeing up the occupied memory.
Ex: class demo
{
public static void main(String args[ ])
{
int d,a;
try
{
d=0;
a=40/d;
System.out.println(“not printed”);
}
catch(ArithmeticException e)
{
System.out.println(“divide by zero error”);
}
finally
{
System.out.println(“final block statement executed”);
}
}
} Output:
Divide by zero error
Final block statement
executed

******

I BSc, III sem Dept of Computer


Science, GFGC, Tiptur

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy