0% found this document useful (0 votes)
3 views25 pages

OOP java-unit 2

The document provides an overview of Java I/O operations, detailing the use of streams for input and output, including byte and character streams, and examples for file handling. It also covers exception handling in Java, explaining checked and unchecked exceptions, the use of keywords like try, catch, finally, throw, and throws, and the concept of custom exceptions. Additionally, it distinguishes between final, finally, and finalize, highlighting their roles in Java programming.

Uploaded by

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

OOP java-unit 2

The document provides an overview of Java I/O operations, detailing the use of streams for input and output, including byte and character streams, and examples for file handling. It also covers exception handling in Java, explaining checked and unchecked exceptions, the use of keywords like try, catch, finally, throw, and throws, and the concept of custom exceptions. Additionally, it distinguishes between final, finally, and finalize, highlighting their roles in Java programming.

Uploaded by

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

AXIS INSTITUTE OF TECHNOLOGY AND MANAGEMENT

UNIT-II
JAVA I/O TUTORIAL

Java I/O (Input and Output) is used to process the input and produce the
output.

Java uses the concept of stream to make I/O operation fast. The java.io
package contains all the classes required for input and output operations.

We can perform file handling in java by Java I/O API.


Stream

A stream is a sequence of data.In Java a stream is composed of bytes. It's


called a stream because it is like a stream of water that continues to flow.

In java, 3 streams are created for us automatically. All these streams are
attached with console.

1) System.out: standard output stream

2) System.in: standard input stream

3) System.err: standard error stream

Byte Based Character Based


Input Output Input (Reader) Output (Writer)
Basic InputStream OutputStream InputStreamReader OutputStreamWriter
Arrays ByteArrayInputStream ByteArrayOutputStream CharArrayReader CharArrayWriter
Files FileInputStream FileOutputStream FileReader FileWriter
Random Access RandomAccessFile RandomAccessFile N/A N/A
Pipes PipedInputStream PipedOutputStream PipedReader PipedWriter
Buffering BufferedInputStream BufferedOutputStream BufferedReader BufferedWriter
Filtering FilterInputStream FilterOutputStream FilterReader FilterWriter
Pushback PushbackInputStream N/A PushbackReader N/A
Parsing StreamTokenizer N/A LineNumberReader N/A
Strings N/A N/A StringReader StringWriter
Data DataInputStream DataOutputStream N/A N/A
Data -
N/A PrintStream N/A PrintWriter
Formatted
Objects ObjectInputStream ObjectOutputStream N/A N/A
Utilities SequenceInputStream N/A N/A N/A

Byte Streams Java byte streams are used to perform input and output of 8- bit
bytes. Though there are many classes related to byte streams but the most
frequently used classes are, FileInputStream and FileOutputStream.
Following is an example which makes use of these two classes to copy an input

SABIYA FATIMA, ASSISTANT PROFESSOR, CSE


AXIS INSTITUTE OF TECHNOLOGY AND MANAGEMENT

file into an output file:

import java.io.*; public

class CopyFile {

public static void main(String args[]) throws IOException

{
FileInputStream in = null;

FileOutputStream out = null;

try {

in = new FileInputStream("input.txt");

out = new FileOutputStream("output.txt");

int c;

while ((c = in.read()) != -1) {

out.write(c);

}finally {

if (in != null) {

in.close();

if (out != null) {

out.close();

} }

Character Streams Java Byte streams are used to perform input and output of
8-bit bytes, whereas Java Character streams are used to perform input and
output for 16-bit unicode. Though there are many classes related to character
streams but the most frequently used classes are, FileReader and FileWriter.
Though internally FileReader uses FileInputStream and FileWriter uses
FileOutputStream but here the major difference is that FileReader reads two
bytes at a time and FileWriter writes two bytes at a time.

SABIYA FATIMA, ASSISTANT PROFESSOR, CSE


AXIS INSTITUTE OF TECHNOLOGY AND MANAGEMENT

import java.io.*;

public class CopyFile {

public static void main(String args[]) throws IOException


{

FileReader in = null;

FileWriter out = null;

try {

in = new FileReader("input.txt");

out = new FileWriter("output.txt");

int c;

while ((c = in.read()) != -1) {

out.write(c);

}finally {

if (in != null) {

in.close();

if (out != null) {

out.close(); } } } }

import java.io.*;

public class ReadConsole {

public static void main(String args[]) throws IOException

InputStreamReader cin = null;

try {

SABIYA FATIMA, ASSISTANT PROFESSOR, CSE


AXIS INSTITUTE OF TECHNOLOGY AND MANAGEMENT

cin = new InputStreamReader(System.in);

System.out.println("Enter characters, 'q' to quit.");

char c;

do {

c = (char) cin.read();

System.out.print(c);

} while(c != 'q');

}finally {

if (cin != null) {

cin.close();

Java BufferedInputStream Class

Java BufferedInputStream class is used to read information from stream. It


internally uses buffer mechanism to make the performance fast.

1. import java.io.*;
2. public class BufferedInputStreamExample{
3. public static void main(String args[]){
4. try{
5. FileInputStream fin=new FileInputStream("D:\\testout.txt");
6. BufferedInputStream bin=new BufferedInputStream(fin);
7. int i;
8. while((i=bin.read())!=-1){
9. System.out.print((char)i);
10. }
11. bin.close();
12. fin.close();

SABIYA FATIMA, ASSISTANT PROFESSOR, CSE


AXIS INSTITUTE OF TECHNOLOGY AND MANAGEMENT

13. }catch(Exception e){System.out.println(e);}


14. }
15. }

EXCEPTION HANDLING IN JAVA

The exception handling in java is one of the powerful mechanism to handle


the runtime errors so that normal flow of the application can be maintained.
Exception is an abnormal condition. Exception Handling is a mechanism to
handle runtime errors
Hierarchy of Java Exception classes

Types of Exception

SABIYA FATIMA, ASSISTANT PROFESSOR, CSE


AXIS INSTITUTE OF TECHNOLOGY AND MANAGEMENT

There are mainly two types of exceptions: checked and unchecked where
error is considered as unchecked exception. The sun microsystem says there
are three types of exceptions:

1. Checked Exception
2. Unchecked Exception
3. Error

Difference between checked and unchecked exceptions


1) Checked Exception
The classes that extend Throwable class except RuntimeException and Error
are known as checked exceptions e.g.IOException, SQLException etc.
Checked exceptions are checked at compile-time.

2) Unchecked Exception

The classes that extend RuntimeException are known as unchecked


exceptions e.g. ArithmeticException, NullPointerException,
ArrayIndexOutOfBoundsException etc. Unchecked exceptions are not
checked at compile-time rather they are checked at runtime.

3) Error

Error is irrecoverable e.g. OutOfMemoryError, VirtualMachineError,


AssertionError etc.

Java Exception Handling Keywords

There are 5 keywords used in java exception handling.

1. Try catch finally throw throws

Java try-catch

Java try block

Java try block is used to enclose the code that might throw an exception. It
must be used within the method.

Java try block must be followed by either catch or finally block.

Syntax of java try-catch

1. try{
2. //code that may throw exception
3. }catch(Exception_class_Name ref){}

1. public class Testtrycatch2{


2. public static void main(String args[]){

SABIYA FATIMA, ASSISTANT PROFESSOR, CSE


AXIS INSTITUTE OF TECHNOLOGY AND MANAGEMENT

3. try{
4. int data=50/0;
5. }catch(ArithmeticException e){System.out.println(e);}
6. System.out.println("rest of the code...");
7. }
8. }
Java Multi catch block

If you have to perform different tasks at the occurrence of different


Exceptions, use java multi catch block.

Let's see a simple example of java multi-catch block.

1. public class TestMultipleCatchBlock{


2. public static void main(String args[]){
3. try{
4. int a[]=new int[5];
5. a[5]=30/0;
6. }
7. catch(ArithmeticException e){System.out.println("task1 is completed
");}
8. catch(ArrayIndexOutOfBoundsException e){System.out.println("task
2 completed");}
9. catch(Exception e){System.out.println("common task completed");}
10.
11. System.out.println("rest of the code...");
12. }
13. }

Java finally block

Java finally block is a block that is used to execute important code such as
closing connection, stream etc.

Java finally block is always executed whether exception is handled or not.

Java finally block follows try or catch block.

Why use java finally

 Finally block in java can be used to put "cleanup" code such as


closing a file, closing connection etc.

Case 1

Let's see the java finally example where exception doesn't occur.
SABIYA FATIMA, ASSISTANT PROFESSOR, CSE
AXIS INSTITUTE OF TECHNOLOGY AND MANAGEMENT

1. class TestFinallyBlock{
2. public static void main(String args[]){
3. try{
4. int data=25/5;
5. System.out.println(data);
6. }
7. catch(NullPointerException e){System.out.println(e);}
8. finally{System.out.println("finally block is always executed");}
9. System.out.println("rest of the code...");
10. }
11. }

Case 3

Let's see the java finally example where exception occurs and handled.

1. public class TestFinallyBlock2{


2. public static void main(String args[]){
3. try{
4. int data=25/0;
5. System.out.println(data);
6. }
7. catch(ArithmeticException e){System.out.println(e);}
8. finally{System.out.println("finally block is always executed");}
9. System.out.println("rest of the code...");
10. }
11. }

Java throw keyword

The Java throw keyword is used to explicitly throw an exception.

We can throw either checked or uncheked exception in java by throw


keyword. The throw keyword is mainly used to throw custom exception. We
will see custom exceptions later.

The syntax of java throw keyword is given below.

1. throw exception;

1. public class TestThrow1{


2. static void validate(int age){
3. if(age<18)
4. throw new ArithmeticException("not valid");
5. else
6. System.out.println("welcome to vote");
7. }

SABIYA FATIMA, ASSISTANT PROFESSOR, CSE


AXIS INSTITUTE OF TECHNOLOGY AND MANAGEMENT

8. public static void main(String args[]){


9. validate(13);
10. System.out.println("rest of the code...");
11. }
12. }

Java throws keyword

The Java throws keyword is used to declare an exception. It gives an


information to the programmer that there may occur an exception so it is
better for the programmer to provide the exception handling code so that
normal flow can be maintained.

Exception Handling is mainly used to handle the checked exceptions. If


there occurs any unchecked exception such as NullPointerException, it is
programmers fault that he is not performing check up before the code being
used.

Syntax of java throws

1. return_type method_name() throws exception_class_name{


2. //method code
3. }

import java.io.*;
class M{
void method()throws IOException{
throw new IOException("device error");
} }
public class Testthrows2{
public static void main(String args[]){
try{
M m=new M();
m.method();
}catch(Exception e){System.out.println("exception handled");}
System.out.println("normal flow...");
} }

Java Custom Exception

If you are creating your own Exception that is known as custom exception or
user-defined exception. Java custom exceptions are used to customize the
exception according to user need.

Let's see a simple example of java custom exception.

1. class InvalidAgeException extends Exception{


SABIYA FATIMA, ASSISTANT PROFESSOR, CSE
AXIS INSTITUTE OF TECHNOLOGY AND MANAGEMENT

2. InvalidAgeException(String s){
3. super(s);
4. }
5. }

1. class TestCustomException1{
2.
3. static void validate(int age)throws InvalidAgeException{
4. if(age<18)
5. throw new InvalidAgeException("not valid");
6. else
7. System.out.println("welcome to vote");
8. }
9.
10. public static void main(String args[]){
11. try{
12. validate(13);
13. }catch(Exception m){System.out.println("Exception occured:
"+m);}
14.
15. System.out.println("rest of the code..."); }}

Question: Difference Between throw and throws


The main differences between throw and throws in Java are as follows:
Feature throw throws

It is used to declare that a


It is used to explicitly throw an
method might throw one or
exception.
Definition more exceptions.

It is used inside a method or a block of It is used in the method


Location code. signature.

It is only used for checked


It can throw both checked and exceptions. Unchecked
unchecked exceptions. exceptions do not
Usage require throws

The method’s caller is


The method or block throws the
responsible for handling the
exception.
Responsibility exception.

Stops the current flow of execution It forces the caller to handle the
Flow of Execution immediately. declared exceptions.

SABIYA FATIMA, ASSISTANT PROFESSOR, CSE


AXIS INSTITUTE OF TECHNOLOGY AND MANAGEMENT

Feature throw throws

throw new public void myMethod() throws


Example ArithmeticException(“Error”); IOException {}

Question: difference between final, finally, finalize().


Answer:
the final, finally, and finalize keywords play an important role in exception handling. The main
difference between final, finally, and finalize is,
 final: The “final” is the keyword that can be used for immutability and restrictions in variables,
methods, and classes.
 finally: The “finally block” is used in exception handling to ensure that a certain piece of code is
always executed whether an exception occurs or not.
 finalize: finalize is a method of the object class, used for cleanup before garbage collection.
final vs finally vs finalize
Aspect final finally finalize

The finally block in


final keyword applies
exception handling is finalize is a method of
restrictions on variable,
used with try-catch object class
method and classes.
Definition block.

The code that is written


finalize method in Java
Prevent modification of inside finally block is
is used to perform
variables, inheritance of always executed after
cleanup operations
classes, or overriding of the try-catch block
before an object is
methods. whether an exception
garbage collected.
Purpose occurs or not .

Objects, specifically by
Variables, methods, and Only within a try-
Can be used overriding the method
classes. catch block.
with in a class

Called by the garbage


collector when an object
Executes when Always executed after
is about to be deleted,
declared. try-catch block.
but it’s not guaranteed
Execution to run.

final Keyword
The final keyword in Java is used with variables, methods, and also with classes to restrict modification.
Syntax:
// Constant value
final int a = 100;
Example: The below Java program demonstrates the value of the variable cannot be changed once
initialized.

SABIYA FATIMA, ASSISTANT PROFESSOR, CSE


AXIS INSTITUTE OF TECHNOLOGY AND MANAGEMENT

// Java Program to demonstrate


// the final keyword with variable
class A {
public static void main(String[] args)
{
// Non final variable
int a = 5;

// final variable
final int b = 6;

// modifying the non final variable


a++;

// modifying the final variable


// Immediately gives Compile Time error
b++;
}
}
Output:

Note: If we declare any variable as final, we can’t modify its contents since it is final, and if we modify it
then we get Compile Time Error.
In the above example, we used the final keyword to declare a variable that cannot be modified after its
initialization. Similarly, the final keyword can also be applied to methods and classes in Java to
impose certain restrictions.
finally Keyword
The finally keyword in Java is used to create a block of code that always executes after the try block,
regardless of whether an exception occurs or not.
Syntax:
try {
// Code that might throw an exception
} catch (ExceptionType e) {
// Code to handle the exception
} finally {
// Code that will always execute
}
Example: The below Java program demonstrates the working of finally block in exception handling.
// Java program to demonstrate
// the working of finally block
public class Geeks {
public static void main(String[] args)
{

try {
System.out.println("Inside try block");
int result
= 10 / 0; // This will cause an exception
SABIYA FATIMA, ASSISTANT PROFESSOR, CSE
AXIS INSTITUTE OF TECHNOLOGY AND MANAGEMENT

}
catch (ArithmeticException e) {
System.out.println("Exception caught: "
+ e.getMessage());
}
finally {
System.out.println(
"finally block always execute");
}
}
}
Output:

Explanation: The try block attempts a division by zero, causing an ArithmeticException. The finally block
executes, whether an exception occurs, ensuring cleanup or mandatory code execution.
finalize() Method
The finalize() method is called by the Garbage Collector just before an object is removed from memory. It
allows us to perform clean up activity. Once the finalized method completes, Garbage Collector destroys
that object.finalize method is present in the Object class.
Syntax:
protected void finalize throws Throwable{}
Example: The below Java program demonstrates the working of finalize() method in context of garbage
collection.
// Java Program to demonstrates
// the working of finalize() Method
import java.util.*;

public class Geeks {


public static void main(String[] args)
{
Geeks g = new Geeks();

System.out.println("Hashcode is: " + g.hashCode());

// Making the object eligible for garbage collection


g = null;

System.gc();

// Adding a short delay to allow GC to act


try {
Thread.sleep(1000);
}
catch (InterruptedException e) {
e.printStackTrace();
SABIYA FATIMA, ASSISTANT PROFESSOR, CSE
AXIS INSTITUTE OF TECHNOLOGY AND MANAGEMENT

System.out.println("End of the garbage collection");


}

// Defining the finalize method


@Override protected void finalize()
{
System.out.println("Called the finalize() method");
}
}
Output:

Explanation: In the above example, an object “g” is created, and its hash code is printed. The object is
made eligible for garbage collection by setting it to null and invoking System.gc().

MULTI THREADING IN JAVA

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.

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.

What is Thread in java

A thread is a lightweight sub process, a smallest unit of processing. It is a


separate path of execution.
Threads are independent, if there occurs exception in one thread, it doesn't
affect other threads. It shares a common memory area.

SABIYA FATIMA, ASSISTANT PROFESSOR, CSE


AXIS INSTITUTE OF TECHNOLOGY AND MANAGEMENT

Life cycle of a Thread (Thread States)

1. New
2. Runnable
3. Running
4. Non-Runnable (Blocked)
5. Terminated

A thread can be in one of the five states. According to sun, there is only 4
states in thread life cycle in java new, runnable, non-runnable and
terminated. There is no running state.

But for better understanding the threads, we are explaining it in the 5


states.

The life cycle of the thread in java is controlled by JVM.

The java thread states are as follows:

1. New
2. Runnable
3. Running
4. Non-Runnable (Blocked)
5. Terminated

1) New
SABIYA FATIMA, ASSISTANT PROFESSOR, CSE
AXIS INSTITUTE OF TECHNOLOGY AND MANAGEMENT

The thread is in new state if you create an instance of Thread class but
before the invocation of start() method.
2) Runnable

The thread is in runnable state after invocation of start() method, but the
thread scheduler has not selected it to be the running thread.

3) Running

The thread is in running state if the thread scheduler has selected it.

4) Non-Runnable (Blocked)

This is the state when the thread is still alive, but is currently not eligible to
run.

5) Terminated

A thread is in terminated or dead state when its run() method exits.


How to create thread

There are two ways to create a thread:

1. By extending Thread class


2. By implementing Runnable interface.

Thread class:
Thread class provide constructors and methods to create and perform
operations on a thread. Thread class extends Object class and implements
Runnable interface.

Commonly used Constructors of Thread class:


 Thread()
 Thread(String name)
 Thread(Runnable r)
 Thread(Runnable r,String name)

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 void join(): waits for a thread to die.

SABIYA FATIMA, ASSISTANT PROFESSOR, CSE


AXIS INSTITUTE OF TECHNOLOGY AND MANAGEMENT

public void join(long miliseconds): waits for a thread to die for the
specified miliseconds.

public int getPriority(): returns the priority of the thread.

public int setPriority(int priority): changes the priority of the


thread.

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 current 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.

public void setDaemon(boolean b): marks the thread as daemon or


user thread.

public void interrupt(): interrupts the thread.

public boolean isInterrupted(): tests if the thread has been


interrupted.

public static boolean interrupted(): tests if the current thread has


been interrupted.
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().

1. public void run(): is used to perform action for a thread.

Starting a thread:

SABIYA FATIMA, ASSISTANT PROFESSOR, CSE


AXIS INSTITUTE OF TECHNOLOGY AND MANAGEMENT

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.

1) Java Thread Example by extending Thread class

1. class Multi extends Thread{


2. public void run(){
3. System.out.println("thread is running...");
4. }
5. public static void main(String args[]){
6. Multi t1=new Multi();
7. t1.start();
8. }
9. }

2) Java Thread Example by implementing Runnable


interface

1. class Sample implements Runnable{


2. public void run(){
3. System.out.println("Thread is running...");
4. }
5.
6. public static void main(String args[]){
7. Sample s=new Sample();
8. Thread t1 =new Thread(s);
9. t1.start();
10. }
11. }

Sleep method in java

The sleep() method of Thread class is used to sleep a thread for the specified
amount of time.

Syntax of sleep() method in java

The Thread class provides two methods for sleeping a thread:

 public static void sleep(long miliseconds)throws InterruptedException


 public static void sleep(long miliseconds, int nanos)throws
SABIYA FATIMA, ASSISTANT PROFESSOR, CSE
AXIS INSTITUTE OF TECHNOLOGY AND MANAGEMENT

InterruptedException

Example of sleep method in java

1. class Ex extends Thread{


2. public void run(){
3. for(int j=1;j<5;j++){
4. try{Thread.sleep(500);}catch(InterruptedException e){System.out.pri
ntln(e);}
5. System.out.println(j);
6. }
7. }
8. public static void main(String args[]){
9. Ex t1=new Ex();
10. Ex t2=new Ex();
11.
12. t1.start();
13. t2.start();
14. }
15. }

The join() method

The join() method waits for a thread to die. In other words, it causes the
currently running threads to stop executing until the thread it joins with
completes its task.

Syntax:
public void join()throws InterruptedException

public void join(long milliseconds)throws InterruptedException

Example of join() method

1. class Sample extends Thread{


2. public void run(){
3. for(int i=1;i<=5;i++){
4. try{
5. Thread.sleep(500);
6. }catch(Exception e){System.out.println(e);}
7. System.out.println(i);
8. } }
9. public static void main(String args[]){
10. Sample t1=new Sample ();
11. Sample t2=new Sample ();
12. Sample t3=new Sample ();
13. t1.start();
SABIYA FATIMA, ASSISTANT PROFESSOR, CSE
AXIS INSTITUTE OF TECHNOLOGY AND MANAGEMENT

14. try{
15. t1.join();
16. }catch(Exception e){System.out.println(e);}
17. t2.start();
18. t3.start();
19. } }

getName(),setName(String) and getId() method:

public String getName()

public void setName(String name)

public long getId()

1. class Sample1 extends Thread{


2. public void run(){
3. System.out.println("running...");
4. }
5. public static void main(String args[]){
6. Sample1t1=new Sample1 ();
7. Sample1 t2=new Sample1 ();
8. System.out.println("Name of t1:"+t1.getName());
9. System.out.println("Name of t2:"+t2.getName());
10. System.out.println("id of t1:"+t1.getId());
11. t1.start();
12. t2.start();
13. t1.setName("Sonoo Jaiswal");
14. System.out.println("After changing name of t1:"+t1.getName());

15. }}

Priority of a Thread (Thread Priority):


Each thread have a priority. Priorities are represented by a number between
1 and 10. In most cases, thread schedular schedules the threads according
to their priority (known as preemptive scheduling). But it is not guaranteed
because it depends on JVM specification that which scheduling it chooses.

3 constants defined in Thread class:


1. public static int MIN_PRIORITY
2. public static int NORM_PRIORITY
3. public static int MAX_PRIORITY

Default priority of a thread is 5 (NORM_PRIORITY). The value of


MIN_PRIORITY is 1 and the value of MAX_PRIORITY is 10.
Example of priority of a Thread:
SABIYA FATIMA, ASSISTANT PROFESSOR, CSE
AXIS INSTITUTE OF TECHNOLOGY AND MANAGEMENT

1. class TestMultiPriority1 extends Thread{


2. public void run(){
3. System.out.println("running thread name is:"+Thread.currentThread
().getName());
4. System.out.println("running thread priority is:"+Thread.currentThre
ad().getPriority());
5.
6. }
7. public static void main(String args[]){
8. TestMultiPriority1 m1=new TestMultiPriority1();
9. TestMultiPriority1 m2=new TestMultiPriority1();
10. m1.setPriority(Thread.MIN_PRIORITY);
11. m2.setPriority(Thread.MAX_PRIORITY);
12. m1.start();
13. m2.start();
14.
15. }
16. }

ThreadGroup in Java

Java provides a convenient way to group multiple threads in a single object.


In such way, we can suspend, resume or interrupt group of threads by a
single method call.

Constructors of ThreadGroup class

There are only two constructors of ThreadGroup class.

No. Constructor Description


creates a thread group with given
1) ThreadGroup(String name)
name.
ThreadGroup(ThreadGroup parent, creates a thread group with given
2) String name) parent group and name.

SABIYA FATIMA, ASSISTANT PROFESSOR, CSE


AXIS INSTITUTE OF TECHNOLOGY AND MANAGEMENT

ThreadGroup Example

File: ThreadGroupDemo.java

1. public class ThreadGroupDemo implements Runnable{


2. public void run()
3. {
4. System.out.println(Thread.currentThread().getName());
5. }
6. public static void main(String[] args)
7. {
8. ThreadGroupDemo runnable = new ThreadGroupDemo();
9. ThreadGroup tg1 = new ThreadGroup("Parent ThreadGroup");
10.
11. Thread t1 = new Thread(tg1, runnable,"one");
12. t1.start();
13. Thread t2 = new Thread(tg1, runnable,"two");
14. t2.start();
15. Thread t3 = new Thread(tg1, runnable,"three");
16. t3.start();
17.
18. System.out.println("Thread Group Name: "+tg1.getName()
);
19. tg1.list();
20.
21. }
22. }

1. class TestMultitasking1 extends Thread{


2. public void run(){
3. System.out.println("task one");
4. }
5. public static void main(String args[]){
6. TestMultitasking1 t1=new TestMultitasking1();
7. TestMultitasking1 t2=new TestMultitasking1();
8. TestMultitasking1 t3=new TestMultitasking1();
9.
10. t1.start();
11. t2.start();
12. t3.start();
13. }
14. }

Synchronization in Java

Synchronization in java is the capability to control the access of multiple


threads to any shared resource.

SABIYA FATIMA, ASSISTANT PROFESSOR, CSE


AXIS INSTITUTE OF TECHNOLOGY AND MANAGEMENT

Java Synchronization is better option where we want to allow only one


thread to access the shared resource.

Why use Synchronization

The synchronization is mainly used to

1. To prevent thread interference.


2. To prevent consistency problem.

Types of Synchronization

There are two types of synchronization

1. Process Synchronization
2. Thread Synchronization

Thread Synchronization

There are two types of thread synchronization mutual exclusive and inter-
thread communication.

1. Mutual Exclusive
1. Synchronized method.
2. Synchronized block.
3. static synchronization.
2. Cooperation (Inter-thread communication in java)

Mutual Exclusive

Mutual Exclusive helps keep threads from interfering with one another while
sharing data. This can be done by three ways in java:

1. by synchronized method
2. by synchronized block
3. by static synchronization

Concept of Lock in Java

Synchronization is built around an internal entity known as the lock or


monitor. Every object has an lock associated with it. By convention, a thread
that needs consistent access to an object's fields has to acquire the object's
lock before accessing them, and then release the lock when it's done with
them.

From Java 5 the package java.util.concurrent.locks contains several lock


implementations.

SABIYA FATIMA, ASSISTANT PROFESSOR, CSE


AXIS INSTITUTE OF TECHNOLOGY AND MANAGEMENT

1. //example of java synchronized method


2. class Table{
3. synchronized void printTable(int n){//synchronized method
4. for(int i=1;i<=5;i++){
5. System.out.println(n*i);
6. try{
7. Thread.sleep(400);
8. }catch(Exception e){System.out.println(e);}
9. }
10.
11. }
12. }
13.
14. class MyThread1 extends Thread{
15. Table t;
16. MyThread1(Table t){
17. this.t=t;
18. }
19. public void run(){
20. t.printTable(5);
21. }
22.
23. }
24. class MyThread2 extends Thread{
25. Table t;
26. MyThread2(Table t){
27. this.t=t;
28. }
29. public void run(){
30. t.printTable(100);
31. }
32. }
33.
34. public class TestSynchronization2{
35. public static void main(String args[]){
36. Table obj = new Table();//only one object
37. MyThread1 t1=new MyThread1(obj);
38. MyThread2 t2=new MyThread2(obj);
39. t1.start();
40. t2.start();
41. }
42. }

Inter-thread communication in Java

Inter-thread communication or Co-operation is all about allowing


synchronized threads to communicate with each other.

SABIYA FATIMA, ASSISTANT PROFESSOR, CSE


AXIS INSTITUTE OF TECHNOLOGY AND MANAGEMENT

Cooperation (Inter-thread communication) is a


mechanism in which a thread is paused running in
its critical section and another thread is allowed to
enter (or lock) in the same critical section to be
executed.It is implemented by following methods of
Object class:

 wait()
 notify()
 notifyAll()

1) 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.

The current thread must own this object's monitor, so it


must be called from the synchronized method only otherwise
it will throw exception.

Method Description

public final void wait()throws


waits until object is notified.
InterruptedException

public final void wait(long timeout)throws waits for the specified


InterruptedException amount of time.

2) 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. The choice is arbitrary
and occurs at the discretion of the implementation.
Syntax:

public final void notify()

3) notifyAll() method

Wakes up all threads that are waiting on this object's

monitor. Syntax: public final void notifyAll()

SABIYA FATIMA, ASSISTANT PROFESSOR, CSE

You might also like