0% found this document useful (0 votes)
2 views21 pages

java_unit_4

Introduction to java , programming with java.

Uploaded by

manohar
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)
2 views21 pages

java_unit_4

Introduction to java , programming with java.

Uploaded by

manohar
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/ 21

MULTITHREADED PROGRAMMING

1) Introduction
2) Thread States
3) Creating a Multiple Threads
4) Thread Priorities

INTRODUCTION
Java is a multithreaded programming language which means we can develop
multithreaded program using Java. A multithreaded program contains two or more parts that
can run concurrently and each part can handle different task at the same time making optimal
use of the available resources specially when your computer has multiple CPUs.

By definition multitasking is when multiple processes share common processing resources


such as a CPU. Multithreading extends the idea of multitasking into applications where you
can subdivide specific operations within a single application into individual threads. Each of
the threads can run in parallel. The OS divides processing time not only among different
applications, but also among each thread within an application.

Multithreading enables to write in a way where multiple activities can proceed concurrently
in the same program.

THREAD STATES
During the life time of a thread there are many states it can enter. They are

A. NewBorn state
B. Runnable state
C. Running State
D. Blocked state / Waiting State
E. Dead state
A thread is always in any one of these five states.It can move from one state to another via a
variety of ways as shown below

Fig
New Born state :
when we create a thread object, the thread is born and is said to be in new born state.
The thread is not yet scheduled for running .At this state, we can do only one of the
following things with it.
 Schedule it for running using start() method.
 Kill it using stop() method.

If scheduled, it moves to the runnable state.

A. Runnable State:
 The runnable state means that the thread is ready for execution and is waiting for
availability of the processor.i.e the thread has joined the queue of threads that are
waiting for execution.
 If all threads have equal priority, then they are given time slots for execution in
Round Robin fashion,i.e FCFS manner.
 The thread that relinguishes control joins the queue at the end & again waits for its
turn.this process of assigning time to threads is known as time slicing.

B. Running State:
 Running means that the processor has given its time to the thread for its execution.
 The thread runs until it relinguishes its control in one of the following situations.
 It has been suspended using suspend().a suspended thread can be received by using
the resume() method.
 It has been made to sleep. we can put a thread to sleep for a specified time period
using the method sleep(time)where time is in milliseconds.
 Hence the thread is out of queue during this time period.
 The thread re-enters the runnable state as soon as this time period is
elapsed.
 It has been told to wait until some event occurs. This is done using the wait()
method.
 The thread can schedule to run again using the notify()
method.

C. Blocked state:
 A thread can also be temporarily suspended or blocked from entering into the
runnable and subsequently running state by using either of the following thread
methods.

Sleep() // blocked for a specified

time Suspended() // blocked until

further orders

Wait() // blocked until certain condition occurs.

 These methods cause the thread to go into the blocked sate. The thread will return
to runnable state when the specified time is elapsed in the case of sleep(),the
resume() method is invoked in case of suspend(),and notify() method is called in
case of wait().
D. Dead State:
 Every thread has a life cycle .A running thread ends its life when it has completed
executing its run().it is natural death.
 However, we can kill it by using stop message to it at any stage.Thus causing
premature death to it.

CREATING MULTIPLE THREADS

 Creating threads in java is simple. Threads in java can be created in two ways
1) By extending the thread class.
2) By implementing the runnable interface.

1) Creating threads by extending the thread class:


 Define a class that extends thread class and override its run()with the code required by
the thread. Steps to create thread by extending thread class are
a) Declaring the class
b) Implementing the run() method.
c) Starting New Thread.
a) Declaring the class:
 declare the class by extending the thread class as:
Class MyThread extends Thread
{
----------
----------
}
b) Implementing the run() method:
 the run method is the heart and soul of any thread.
 We have to override this method in order to implement the code to be executed by our
thread.
 It makes up the entire body of a thread and is the only method in which the threads
behavior can be implemented.
 The basic impolementation of run() will look
like Public void run()
{
Thread code
}
 When we start new thread ,java calls the threads run() method.
C )Starting New Thread:
 create a thread object and call the start() method to initiate the thread execution.
 To create and run an instance of our thread class, we must write the
following: MyThreadt1=new MyThread();
T1.start();
 The first line instantiates a new object of class MyThread.
 The second line calls start() causing the thread to move into runnable state.
 Then, the java runtime will schedule the thread to run by invoking its run().Hence the
thread is said to be in Running state.
Ex: Class A Extends Thread
{
Public void run()
{
Tr
y
{ For(int i=1;i<=5;i++)
{
S.o.p(“from thread A:”+i);
Thread.sleep(100);
}
}
Catch(InterruptEx ception e)
{
S.o.p(e);
}
}
}

Class B extends Thread


{
Public void run()
{
Try
{
For(int i=1;i<=5;i++)
{
S.o.p(“from thread B :”+i);
Thread.sleep(100);
}
}
Catch(InterruptException e)
{
S.o.p(e);
}
}
}
Class ThreadDemo
{
Psvm(String args[ ] )
{
A t1=new A();
B t1=new
B();
T1.start();
T2.start();
}
}
Z:\> javac ThreadDemo.java
Z:\> java ThreadDemo
From thread B:1
From thread A : 1
Frrom thread B :2
From thead A:2
From thread B : 5
From thread B :3
From thread A : 3
From thread B :4
From thread A :4
From thread B :
5 From thread A:
5
2. Creating threads by implementing runnable interface:
Define a class that implements Runnable interface .the runnable interface has only one
method ,run() that is to be defined in method with the code to be executed by thread.
Steps to create thread by implementing runnable interface.
a.Declaring the class
b.Implementing the run() method.
c. Starting New Thread.

a.Declaring the class:


The easiest way to create a thread is to create a class that implements the runnable interface.
Declare a class as
Class MyThread implements Runnable
{
----------
----------
}
b.Implementing the run():to implement runnable , which is declared as
public void run()
{
----------
----------
}
C.Starting New thread:after creating a class that implements runnable ,instantiate an object oif
type thread from within that class .
Thread (Runnable threadob, string threadName).

Ex:
Class A implements thread
{
Public void run()
{
Try
{
For(int i=1;i<=5;i++)
{
S.o.p(“from thread A:”+i);
Thread.sleep(100);
}
}
Catch(InterruptException e)
{
S.o.p(e);
}
}
}
Class B implements Thread
{
Public void run()
{
Try
{
For(int i=1;i<=5;i++)
{
S.o.p(“from thread B :”+i);
Thread.sleep(100);
}
}
Catch(InterruptException e)
{
S.o.p(e);
}
}
}
Class ThreadDemo
{
Psvm(String args[ ] )
{
A t1=new A();
B t1=new B();
Thread th1= new Thread(t1);
Thread th2=new Thread(t2);
Th1.start();
Th2.start();
}
}
Z:\> javac ThreadDemo.java
Z:\> java ThreadDemo
From thread B:1
From thread A : 1
Frrom thread B :2
From thead A:2
From thread B : 5
From thread B :3
From thread A : 3
From thread B :4
From thread A :4
From thread B :
5 From thread A:
5
Choosing an approach:
So, if you will not be over riding any of threads other methods ,it is probably best simply to
implement runnable.
In short,if we want to override only run() method better to use Runnable interface .If it
requires to extend we have no choice but to implement the runnable interface since java
classes cannot have two super classs.

THREAD PRIORITIES AND SCHEDULING


 In java, each thread is assigned a priority,which affects the order in which it is
scheduled for running.
 The thread of the same priority are given equal treatment by java scheduler and
therefore they share the processor on a first come, first serve basis.
 Java permits us to set and get priority of a thread using setPriority() and getPriority()
as follows

ThreadName.setPriority(int Number)
ThreadName.getPriority()
 Thread class constants are

MIN_PRIORITY=1
MAX_PRIORITY=10
NORM_PRIORITY=5
 NORM_PRIORIty is the default priority.
 Java run time system usually applies one of the two following strategies
 Preemptive scheduling:if the thread has a higher priority then the current running
thread leaves runnable state and higher priority enter to runnable state.
 Time-sliced(Round robin):A running thread is allowed to be execute for the fixed
time, after completion of time , current thread indicates to the another thread to enter it
in the runnable state.
 Example

Class A extends Thread


{
Public void run()
{
S.o.p(“thread A started”);
For(int i=1;i<=4;i++) {
S.o.p(“\t from thread A:i= “+i);
}
S.o.p(“exit from A”);
}
Class B extends Thread{
{
Public void run

S.o.p(“thread B started”);
For(int j =1 j<=4; ++) {
S.o.p(“\t from thread B:j= “+j);
}
S.o.p(“exit from B ”);
}
Class C extends Thread
{
Public void run
{
S.o.p(“thread C started”);
For(int k=1 k<=4; k++) {
S.o.p(“\t from thread C:k= “+k);
}
S.o.p(“exit from c ”);}
}
Class ThreadPriority
{
psvm(String args[ ])
{
A t1=new A();
B t2=
new
B();
C t3=
new
C();
t3.setPriority(Thread.MAX_PRI
ORITY); t2.
setPriority(t1.getPriority()+1);
t1.
setPriority(Threag.MIN_PRIORI
TY); S.o.p(“start Thread A”);
t1.start();
S.o.p(“start
Thread B”);
t2.start();
S.o.p(“start
Thread C”);
t3.start();
ZS.o.p(“end of main thread ”);}
}
}

THREAD SCHEDULING

Java run time system usually applies one of the two following strategies

1. Preemptive scheduling:if the thread has a higher priority then the current running
thread leaves runnable state and higher priority enter to runnable state.

2. Time-sliced(Round robin):A running thread is allowed to be execute for the fixed


time, after completion of time , current thread indicates to the another thread to enter
it in the runnable state.

STREAMS AND FILES

A Stream represents flow of data from one place to another place Input
Streams reads or accepts data Output Streams sends or writes data to some
other place
All streams are represented as classes in javaio package The main
advantage of using stream concept is to achieve hardware independence This
is because we need not change the stream in our program even though we
change the hardware
Streams are of two types in Java:
Byte Streams:
Handle data in the form of bits and bytes Byte streams are used to handle any
characters (text), images, audio and video files For example, to store an image
file (gif or jpg), we should go for a byte stream To handle data in the form of
'bytes' the abstract classes: InputStream and OutputStream are used The
important classes of byte streams are:

InputStream

FileInputStream FilterInputStream ObjectInputStream

BufferedInputStream DataInputStream

Byte Stream Classes for Reading Data

Output Stream

FileOutputStream FilterOutputStream ObjectOutputStream

BufferedOutputStream DataOutputStream

Byte Stream Classes for Writing Data


FileInputStream/FileOutputStream: They handle data to be read or written to disk
files FilterInputStream/FilterOutputStream: They read data from one stream and
write it to another stream ObjectInputStream/ObjectOutputStream: They handle
storage of objects and primitive data
Character or Text Streams:
Handle data in the form of characters Character or text streams can always
store and retrieve data in the form of characters (or text) only It means text
streams are more suitable for handling text files like the ones we create in
Notepad They are not suitable to handle the images, audio or video files To
handle data in the form of 'text' the abstract classes: Reader and Writer are used
The important classes of character streams are:
Reader

BufferedReader CharArrayReader InputStreamReader PrintReader

FileReader
Text Stream Classes for Reading Data

Writer

BufferedWriter CharArrayWriter OuputStreamWriter PrintWriter

FileWriter

Text Stream Classes for Writing Data


BufferedReader/BufferedWriter: - Handles characters (text) by buffering them
They provide efficiency
CharArrayReader/CharArrayWriter: - Handles array of characters
InputStreamReader/OutputStreamWriter: - They are bridge between byte streams and
character streams Reader reads bytes and then decodes them into 16-bit unicode
characters Writer decodes characters into bytes and then writes
PrintReader/PrintWriter: - Handle printing of characters on the screen

File: A file represents organized collection of data Data is stored permanently in


the file Once data is stored in the form of a file we can use it in different programs
Program 1: Write a program to read data from the keyboard and write it to a
text file using byte stream classes
//Creating a text file using byte stream classes

import java.io.*;
class CreateFile
{
public static void main(String args[]) throws IOException
{
//attach keyboard to DataInputStream
DataInputStream dis = new DataInputStream (System.in);
//attach the file to FileOutputStream
FileOutputStream fos = new FileOutputStream ("myfile.txt");
//read data from Data Input Stream and write into FileOutputStream
char ch;
System.out.println ("Enter @ at end : " ) ;
while( (ch = (char) dis.read() ) != '@' )
fos.write (ch);
fos.close ();
}
}
Output:

Program 2: Write a program to improve the efficiency of writing data into


a file using BufferedOutputStream
//Creating a text file using byte stream classes
import java.io.*;
class CreateBos
{
public static void main(String args[]) throws IOException
{
//attach keyboard to DataInputStream
DataInputStream dis = new DataInputStream(System.in);
//attach file to FileOutputStream, if we use true then it will open in append
mode
FileOutputStream fos = new FileOutputStream ("myfile", true);
BufferedOutputStream bos = new BufferedOutputStream (fos, 1024);
//Buffer size is declared as 1024 otherwise default buffer size of 512 bytes is used
//read data from DataInputStream and write into FileOutputStream
char ch;
System.out.println ("Enter @ at end : " );
while ( (ch = (char) dis.read() ) != '@' )
bos.write (ch);
bos.close ();
fos.close ();
}
}
Output:

Program 3: Write a program to read data from myfile using FileInputStream


//Reading a text file using byte stream classes
import java.io.*;
class Read1
{
public static void main (String args[]) throws IOException
{
//attach the file to FileInputStream
FileInputStream fis = new FileInputStream ("myfile");
//read data from FileInputStream and display it on the monitor
int ch;
while ( (ch = fis.read() ) != -1 )
System.out.print ((char) ch);
fis.close ();
}
}
Output:

Program 4: Write a program to improve the efficiency while reading data from a
file using BufferedInputStream
//Reading a text file using byte stream classes
import javaio*;
class Read2
{
public static void main(String args[]) throws IOException
{
//attach the file to FileInputStream
FileInputStream fin = new FileInputStream ("myfile");
BufferedInputStream bin = new BufferedInputStream (fin);
//read data from FileInputStream and display it on the monitor
int ch;

while ( (ch = bin.read() ) != -1 )


System.out.print ( (char) ch);
fin.close ();
}
}
Output:

Progr
am 5: Write a program to create a text file using character or text stream
classes
//Creating a text file using character (text) stream classes
import javaio*;
class Create3
{
public static void main(String args[]) throws IOException
{
String str = "This is an Institute" + "\n You are a student"; //take a String
//Connect a file to FileWriter
FileWriter fw = new FileWriter ("textfile");
//read chars from str and send to fw
for (int i = 0; i<str.length () ; i++)
fw.write (str.charAt (i) );
fw.close ();
}
}
Output:
Program 6: Write a program to read a text file using character or text
stream classes //Reading data from file using character (text) stream
classes

import java.io.*;
class Read3
{
public static void main(String args[]) throws IOException
{
//attach file to FileReader
FileReader fr = new FileReader ("textfile");
//read data from fr and display
int ch;
while ((ch = fr.read()) != -1)
System.out.print((char) ch);
//close the file
fr.close ();
}
}
Output:

Note: Use BufferedReader and BufferedWriter to improve the efficiency of


the above two programs.
Serialization of objects:
Serialization is the process of storing object contents into a file The class whose
objects are stored in the file should implement "Serializable' interface of javaio
package Serializable interface is an empty interface without any members and
methods, such an interface is called 'marking interface' or 'tagging interface'
Marking interface is useful to mark the objects of a class for a special purpose For
example, 'Serializable' interface marks the class objects as 'serializable' so that they
can be written into a file If serializable interface is not implemented by the class,
then writing that class objects into a file will lead to NotSerializableExceptionstatic
and transient variables cannot be serialized
De-serialization is the process of reading back the objects from a file

Program 7: Write a program to create Employ class whose objects is to be stored into
a file
//Employ information
import java.io.*;
import java.util.*;
class Employ implements Serializable
{
private int id;
private String name;
private float sal;
private Date doj;
Employ (int i, String n, float s, Date d)
{
id = i;
name = n;
sal = s;
doj = d;
}
void display ()
{
Systemoutprintln (id+ "\t" + name + "\t" + sal + "\t" + doj);
}
static Employ getData() throws IOException
{
BufferedReader br = new BufferedReader (new InputStreamReader (System.in));
System.out.print ("Enter employ id : ");
Int id = Integer.parseInt(br.readLine());
System.out.print ("Enter employ name : ");
String name = br.readLine ();
System.out.print ("Enter employ salary : ");
float sal = Float.parseFloat(br.readLine ());
Date d = new Date ();
Employ e = new Employ (id, name, sal, d);
return e;
}
}

Output:

Program 8: Write a program to show serialization of objects


//ObjectOutputStream is used to store objects to a file
import java.io.*;
import java.util.*;
class StoreObj
{
public static void main (String args[]) throws IOException
{
BufferedReader br = new BufferedReader (new InputStreamReader (Systemin));
FileOutputStream fos = new FileOutputStream ("objfile");
ObjectOutputStream oos = new ObjectOutputStream ( fos );
System.out.print ("Enter how many objects : ");
int n = Integer.parseInt(br.readLine () );
for(int i = 0;i<n;i++)
{
Employ e1 = Employ.getData ();
Oos.writeObject (e1);
}
Oos.close ();
fos.close ();
}
}
Output:

Program 9: Write a program showing deserialization of objects


//ObjectInputStream is used to read objects from a file
import java.io.*;
class ObjRead
{
public static void main(String args[]) throws Exception
{
FileInputStream fis = new FileInputStream ("objfile");
ObjectInputStream ois = new ObjectInputStream
(fis);
try
{
Employ e;
while ( (e = (Employ) ois.readObject() ) != null)
e.display ();
}
catch(EOFException ee)
{
System.out.println ("End of file Reached");
}
finally
{
ois.close();
fis.close ();
}
}
}
Output:

File Class: File class of javaio package provides some methods to know the
properties of a file or a directory We can create the File class object by
passing the filename or directory name to it
File obj = new File (filename);
File obj = new File
(directoryname); File obj = new
File ("path", filename);
File obj = new File ("path", directoryname);
File class Methods:
Methods Description
boolean isFile () Returns true if the File object contains a filename, otherwise false
boolean isDirectory () Returns true if the File object contains a directory name
boolean canRead () Returns true if the File object contains a file which is readable
boolean canWrite () Returns true if the File object contains a file which is writable
boolean canExecute () Returns true if the File object contains a file which is executable
Boolean exists () Returns true when the File object contains a file or directory which
physically exists in the computer
String getParent () Returns the name of the parent directory
String getPath () Gives the name of directory path of a file or directory
String getAbsolutePath () Gives the fully qualified path
long length () Returns a number that represents the size of the file in bytes
boolean delete () Deletes the file or directory whose name is in File object
boolean createNewFile () Automatically crates a new, empty file indicated by File object, if
and only if a file with this name does not yet exist
Program 10: Write a program that uses File class methods
//Displaying file properties import
javaio*;
class FileProp
{
public static void main(String args[])
{
String fname = args [0];
File f = new File (fname);
System.out.println ("File name: " + f.getname ());
System.out.println ("Path:"+ f.getPath ());
System.out.println ("Absolute Path:"+ f.getAbsolutePath ());
System.out.println ("Parent:"+ f.getParent ());
System.out.println ("Exists:"+ f.exists ());
if ( f.exists() )
{
System.out.println("Is writable: "+ f.canWrite ());
System.out.println ("Is readable: "+ f.canRead ());
System.out.println ("Is executable: "+ f.canExecute ());
System.out.println("Is directory: "+ f.isDirectory ());
System.out.println ("File size in bytes: "+ f.length ());
}
}
}
Ouput:

You might also like