0% found this document useful (0 votes)
4 views103 pages

week 6 java (2)

The document provides a detailed demonstration of exception handling mechanisms in Java, covering compile-time and run-time errors, and various methods to handle exceptions such as try-catch blocks, multiple catch statements, and finally blocks. It illustrates how to make programs robust by using exception handling to prevent abrupt terminations and manage errors effectively. The document also discusses advanced concepts like throw clauses and nested try-catch blocks to further enhance error management in Java programming.
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)
4 views103 pages

week 6 java (2)

The document provides a detailed demonstration of exception handling mechanisms in Java, covering compile-time and run-time errors, and various methods to handle exceptions such as try-catch blocks, multiple catch statements, and finally blocks. It illustrates how to make programs robust by using exception handling to prevent abrupt terminations and manage errors effectively. The document also discusses advanced concepts like throw clauses and nested try-catch blocks to further enhance error management in Java programming.
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/ 103

Programming in Java

Prof. Debasis Samanta


Department of Computer Science and Engineering
Indian Institute of Technology, Kharagpur

Lecture – 26
Demonstration – X

So, let us have a demonstration regarding the Exception Handling Mechanism in Java.

(Refer Slide Time: 00:25)

And today’s demonstration includes mainly the compile-time errors, and then what are
the run time errors are there, and then how exception handling mechanism can be
achieved by means of simple try-catch block, try with multiple catch, then multiple error
errors with single catch. And there is another block that can be added with the try-catch
is called the finally, so try-catch-finally block in along with the try-catch block, and then
throw and then throw used in exception handling and then nested try-catch block also.
(Refer Slide Time: 01:08)

So, let us have the first look at the compile-time error. As you know if you run the
program which is not as per the syntax of java programming language. So, the job java
compiler reports all these things as an error as we see here in this program here. We can
see a lot of errors are there and here we can see in the first statement itself start with error
because java is a case sensitive. So, capital C in the class declaration key work is not
allowed.

(Refer Slide Time: 01:38)


So, if we run this program as it is the first execution, so compiler will halt it here
showing this error there. So, we will correct one error at a time as we see the compiler
will report the class error here.

Now, let us quickly remove this error now we can see there is more error and public also
capital P it is not allowed, so let us small capital is there and then again the error is there,
ok. Let us quick to fix it, right. Public and then the system as we see capital S should be
there and then capital S, and then you see all the statement should be terminative
semicolon. So, as there is no semicolon, so we should make the semicolon here again put
the semicolon as we see. So, java compile compiler will compile the program and
whenever it finds an error it will report it and then until this report is fixed, so this
program will not lead to the successful execution of the program.

So, there are a few more errors as we see. Any method should not be declared and
abstract inside a class method as we can see here because it is not an abstract class. So,
there is an error, and then there are few more error as we see those basically compile-
time errors actually.

Now, so after knowing this compile-time error let us have the run time error concept it is
there. Our next illustration to explain the idea is about the run time error. So, let us go to
demonstration 10.2. Here we can declare on class, the name of the class is error and ok,
right.

(Refer Slide Time: 03:22)


As we see this is the one class declaration, let us follow let us have the quick look at the
class declaration here. Now here we can see this program is perfectly there is no
compilation error, as we have compiled it successfully; however, this program will run
but will not run for all. Now, if we run with this one we will see it run for all not for all,
but for some.

For example, for if we run this program with input 1 2 it will run, input 1 2 give, it runs
correctly. Now, 10 20 30, as we see these program will gives an, it is 10 30; 10 20 30.
So, this program also takes this input. Now, what will happen if we give only a single
output? As we see it also ok. So, that is a single input, in this case, it gives an error. So,
this error is basically array index out of bound exception array error it is there.

Now, again four 4.5 and 5 the different error it will basically it is called the exception.
Also, we can see the number format exception error it is there. Now, we will see these
are not actually errors they are called exceptions because in some situation this program
not able to handle this, and this so program is there is no error in the program rather these
programs cannot handle all input that is the cases of exception that is why they are called
exception.

(Refer Slide Time: 05:10)

Now, let us see how we can make our program robust using the exception handling
mechanism it is there. So, let us have the first program there. As we see this program
10.3, this program we see there are lot of exception scope of exception as we see for
example, in statement x; display, display yeah, ok. So, here we can see in that class
demonstration 103 we see a equals to x divided by y. So, there is a scope of an exception
to occur because if y is 0; that means, any function is called with two arguments with the
second argument is 0 and then again there is a possible job exception in integer.percent
in case suppose if we run this with non integer parameter passed through there right.

Now, anyway. So, this program has that it is, it is if we compile it or definitely there is
no compile-time error this means the program does not have any error there. So, if we
run it for two it is no error, but if we run with see first argument other than 0 then, ok; 10
and 0 for example, as we see here two inputs one is 10 and another is 0, because second
input if it is 0 it will basically divide by 0 or arithmetic exception as we see here
arithmetic exception error occurs here. So, this is a case of exception that we can see and
we see this program is therefore, not so robust.

(Refer Slide Time: 07:10)

Now, towards the implementation robust program, we can use simple try-catch. So, this
is the example to show how the simple try-catch can make the program robust.

So, here the point of exception where we just enclose it in the try-catch block, and there
is another source of exception there a equals to integer.percent they are also a source of
exception there. So, we have just put them in the try-catch. Now, this program will run
for any input whatever the input that was not working in for the previous case.
Now, let us run this program with inputs 10 and 0 again. As it was not working there in
this case you see it works there and divide by 0 it reported and then result in 0 returns
this one, ok. So, this way we can; so in previous cases the program was not program was
abnormally terminated rather, but in this case program run successfully, but exception
which occurs it caught and then handle it.

(Refer Slide Time: 08:12)

Now, the next example is basically, so how the robust program can be developed. Again
the same thing, if we run the different cases we can skip let us go to the 10.6 runs the
following program, run the program without exception handling mechanism for some
input.

Let us see have the 106 programs there, yeah. 10.6 program as we see here this program
includes again exception in many regions here in the, for example, string my string, new
string, I, there is a possibility if i is 0 in all points are assignment and then next if my
string 0 equals, ok. We can write it instead of my string 0 you know you just write args 0
if args 0; no if args 0 ok, that is fine it will work ok, if args 0.

Now, let us compile this program and as we see it will work for some input, but not all
output, not all inputs, ok. And again if we run this program first say Java input is capital
J a v a. So, it basically runs this program correctly and I love Java. Now, let us see you
can see this program basically starts at the point here in the last statement. So, an error is
there. It will not work for example, now what will happen if we run this program without
passing any input common line. So, just simply run. It is also giving an error because an
array index out of bound error is there. So, we see this program is erroneous.

Now, let us implement this with multiple catch block.

(Refer Slide Time: 10:08)

So, this is an example to illustrate the try with multiple catch. So, all the errors all the
exception that occurs there in the program can be handled using try or that means, try
will check if exception if any occurs during run time and then corresponding catch will
catch all the exception and then handle them with their proper code here. Here very
simple code that we have used system print l n only.

Now, here there is point one where the error occurs, point two also the error occurs and
point three also the error occurs here. And we just in the process of catching this here
arithmetic exception and then if it is there so first catch is to catch the arithmetic
exception, second catch to null pointer exception, and then the third catch is to array
index out of bound exception. So, this way if we run this program again it will run
successfully, again my string 0 you can check it arg 0 that is all. If the statement, is ok,
fine.
(Refer Slide Time: 11:12)

So, this program is now robust and whatever the situation happens here in the last case it
was working java all the input it is where, but I love java it was not working there. A null
pointer exception java.lang.nullpointerexception where it is? Ok, you just do my string
whatever it is here, ok. Run this some of here is a program, yeah. So, no compile-time
error, yeah. So, there is an error because no input, if we do not give input one error will
be there, if we just simply java a null pointer java.lang (Refer Time: 12:12), yeah.

So, it was working correctly; there are some marks there we have resolving. Anyway, so
now, again if we run this program java without any input, I mean this program without
any input common line output these also it will catch the exception and accordingly
program will not abruptly terminated. Array index out of bound this is why it gives the
error, fine.

So, let us have the next one. This is also another example that multiple errors by a single
catch. So, this example we can see the multiple errors here in the switch statement
actually, in every switch there is an error is there. And then if we run this program as we
have make the program robust by using single try, but the multiple errors are only one try
and then catch is to handle all the catch here you can see catch exception e because of all
the irrespective of the type of error it will catch it. This is the exception is there.
(Refer Slide Time: 13:26)

And this program will; ok. If we run it, it in fact for each switch statement case statement
it will face an exception and this accession will be caught by the catch statement.

(Refer Slide Time: 13:33)

Yeah as we see so all exceptions that occur in the four case statements are caught in the
single catch statement.
(Refer Slide Time: 13:58)

Now, so there is another block that can be added with the try-catch block called the
finally,. So, here is the next program that we can see, ok.

(Refer Slide Time: 14:03)

We can see the block with finally, so all the exception that can be caught by try here the
try statement and then corresponding catch, and then we add it finally, statement here.
And as we see whatever the exception whether occur or not this finally statement will be
executed and it will accordingly the code will be, code will run and then gives the output.
Now, let us run this program as we see the greetings has the three, so this while loop is
successful for three, first three loops, I mean three iterations 0 1 3, but three for the three
because less than 4 means this loop will roll till 3 and for the last one it will report an
error and then we will see the finally, will print this statement accordingly. So, here we
can see it will print high statements all the time, but the next if i less than 3 it will do
nothing but it will be if i greater than 3, ok. So, as we see this is the output here and the
last statement finally, whenever I loop is there fine. So, here we can see that finally block
if it is added with try-catch. So, for every try-catch occurrence this finally will be
executed, this is the main use of the final statement finally statement.

Now, our next illustration to highlights the throw clause in a program and here is
basically the demonstration of the throws.

(Refer Slide Time: 15:35)

As we see as we have discussed in our theoretical discussion a throws clause can throw
an exception explicitly and that exception then can be caught in the try-catch block here.
Now here is a small program segment as we see the name of the class is demonstration
and the score 1010, and here array is a declaration of size 3 and then try for integer i
equal to 0, i less than 4, so 0 1 2 3. As it is an array size 3 definitely for the first array it
is an array index out of bound exception it will be there. So, for i equal to 0 no exception,
i equal to 1 2 no exception, for i equal to 3 the exception will be there.
(Refer Slide Time: 16:27)

Now, this exception will be caught in the try block and then catch will do it and here
actually it will see the different methods those are there in the exception class is invoked
here. For example, getCause, then fillInStackTrace, then getLocalisedMessage,
getMessage whatever it is there. So, it is basically the implementation of exception class
in java.lang.throwable to package and according to this, we can access this method in our
program.

So, this catch whenever it occurs it catch the array index out of bound exception, for that
error it will basically give the all message trace and then regarding the complete
information about the exception that it occurs there via the different methods in that
throwable class. Now, let us run this program and also it has finally method.
(Refer Slide Time: 17:19)

And here you can see within this catch block we include the throw statement it basically
throw the exception to the caller. So, this method if it is called here the method is
basically the name of the method is named the here method is ok. So, here is no caller of
course, so it will not return anything to any other, but if this method is the try-catch block
is inside a method, which basically throw then the throw an exception which basically
returns to the caller here, fine.

So, this is the complete methods are there, if we run it then we can see how this output it
will give for us. So, it is basically showing the exception as we see for others it will give
it. Where is a program compilation? It is here, yeah. So, java array index out of bound
exception for 3 and it gives all the detail information about the exception it is there. So, if
you want to scrutinize this program for further details and then the cause and effects and
everything then all those information will be useful.
(Refer Slide Time: 18:48)

Now, our next example is basically a nested try-catch example. Nested try-catch example
as we have mentioned that a try-catch block can be put inside another try-catch block, so
it is called the nested here now, this is the one program. As you see this program does
not have any error but when we want to run it, it may leads to some exception. Here this
program if it is run for the three different intention, for example, let us run this program
and give the three intentions as we see and when the exception occurs you will see
exactly.

(Refer Slide Time: 19:15)


So, without try-catch this is the implementation and run this program first with 1 2 3 as
an input yeah, so this program is successful at this stage. Now, 1 2 only two inputs it
gives an exception as the array index out of bound exception. Now, again with only
single input it also gives an exception it is also an arithmetic exception. Now, no input it
also gives an error, it is also given the error that, ok. So, we can see, so this program is
vulnerable to three inputs, as we are three cases, as three test data as we have checked it,
but it works only for them. So, an exception is there.

Now, let us see our enmity how this can be robust, make a robust program using try-
catch, nested try-catch.

(Refer Slide Time: 20:13)

Now, here if we see the first blocks 42 by a is basically arithmetic exception and if a
equals to 1 it is an arithmetic exception. So, it is a very similar kind of exception. So, as
it is only one exception, so this can be tried with an only try block. So, this is the outer
try block.

Now, inside again this is another exception if a equal to 2 it is basically the exception is
called array out of bound exception. So, to take care of this exception we put another try-
catch, so inside this one. So, this is an example of a try-catch. As you see the in-out try-
catch caught, I mean try for the array index out of bound exception and catch
accordingly whereas, the outermost try-catch block caught the arithmetic exception here
and cause it. So, this is the idea about the instant try-catch block.
(Refer Slide Time: 21:07)

And now if we run this program and again try with all possible output for which it was
not working in the previous case let us see what will happen, 1 2 3 it is work. Now java 1
2, it is 1 2 it also works, right. It is showing the report; it basically catches the exception
that has been cached. Again 1 it is also seen divide by 0 it is basically the exception has
been caught, and then these also by 0 it is caught.

So, in this case, the program is robust in the sense that in the cause of exception the
program will completes its execution and finally without any abnormal termination or
any causes or loss of data whatever it is there. So, this is a concept of exception handling.
In fact, exception handling is a very important feature in java programming language
scenario, and more practice is required of course.
(Refer Slide Time: 21:54)

Again I advise you to practice all the example that we have used in this demonstration so
that you can practice your own. And then this basically hands-on practice is required to
understand all these things thoroughly, and in case of any doubt and confusion, you are
most welcome to, feel free to ask us. So, thank you for your attention.

Thank you very much and all the best for learning.
Programming in Java
Prof. Debasis Samanta
Department of Computer Science and Engineering
Indian Institute of Technology, Kharagpur

Lecture – 27
Multithreading – I

So, today we shall start about multithreaded programming very new concepts in
programming arena and this multithreaded programming concept is very important to
develop many different type of software. For example, java is best suitable for
developing application software’s such as library management system, word processing
system like this.

It is also equally best suitable for developing system software such as compiler operating
system. Now such system software development is possible using java because of this
features the multithreaded programming concept. Now before going to understand about
the different features so, for the multithreaded programming is concerned first we should
clear our idea about what exactly a multithreading is.

(Refer Slide Time: 01:13)

Now, as the name says the multithreading it is basically the short form of multiple thread
threading actually that is why multithreading. So, definitely so, it is in contrast to single
threading we can say. So, what exactly the concept of single threading is, that here we
can see this is a one example of a class which has one method. So, this is a method as we
see and in this method as the execution takes place from the very first statement to the
next statement, the next statement and so on.

So, this way the multithreaded this way a thread will occurs. So, this way the thread will
occurs starting from this to this direction. So, we can say in other way about that if we
start from with the first statement like so is a begin the next statement, the next
statement, next statement and so on and finally, it will go to the end of the statement.
And this way the threads or the execution that it takes place is called a single threaded
manner and then the execution is called the single threaded execution.

Now, in contrast to this single threaded execution there is a concept called multi thread
execution.

(Refer Slide Time: 02:51)

Here is an example that we can use this example to explain the concept of multiple
threading here. So, execution here will start from this point suppose and then if we can
bifurcate this execution into 3 or more here for example, bifurcation into this is a one
part, this another part and this another part then it is called that. So, the execution will
take place in a concurrent manner; that means, it will run this part, it will run this part
and it will run this part. So, all 3 executions can take place in a parallel manner or in a
concurrent manner then we can say this is a multi threaded execution.
So, this is a idea about the multithreading now here one important point that we should
note here is that whenever the threads are in execution all this threads can exchange the
data among themselves. Here for example, the result that is produced by these thread,
can be used by these thread or vice versa like this, also they can use a global data among
them also not global data means common data among them also anyway. So, these
thread whenever they execute, they execute in parallel and then the data exchange is
quite possible among them

Now, as an another example we can consider one more another example.

(Refer Slide Time: 04:21)

Let us consider this is a one part of the program and here as we see this program or you
can say the main method consist of different modules. So, this is a one module, this
another module, search module, clean module so, different modules are there. Now if
this program executes in a single threaded manner this means that this module will start
it is execution completes then only the next module start and so on. So, this way the
single threaded execution will takes place. So, pictorially the single threaded execution
will look like this pictorially the single threaded execution will look like this so, it is this
way.

Now on the other hand if the same thing which if we run in a multiple threaded then it
will look like this. So, if we run in a multiple threaded then as we see here. So, in a
multiple threaded as you see. So, after the reading operation is there it will bifurcate into
3 different what is called the parts, the sort, calculate and search. So, what you can say at
this stage there are 3 threads, sort thread, calculate ThreadAnd search thread. They can
execute in parallel and once all this threads are finished their execution it will come to
this ThreadAnd then print will execute. So, this way this parts can execute in a multiple
threaded manner, this is single threaded manner. So, this is a concept of multithreaded
execution or is a program.

(Refer Slide Time: 06:33)

So, now, we have learnt about the idea about the multithreading how it works is there,
there are many example that can be given why are the multithreaded execution is
obvious. So, whenever we are using our system computer there are many task which is
basically works in a continuous concurrent manner. For example, when you are reading
web page at the same time you can type into using word processor and at the same time
you can play your music. So, all the things are going in parallel. So, for everything for
playing a music there is a one thread for browsing the information from the internet one
thread whenever you are typing something using a word processor application is another
ThreadAnd all these things.

Now so there are many applications where the multithreaded way the executions are
there and to be carried out. So, that we can achieve maximum things from the system,
now how this multithreading actually can be achieved in our system, there are in fact, 2
ways the multitasking and multiprocessing. So, in our few next slide we should
understand about what is the multithreading and multitasking is.

(Refer Slide Time: 07:53)

So, here the multitasking is also alternatively called the time sharing; that means, if we
have to run the multiple programs together. So, is a part of one program can share the
CPU time or some other resource time and at the same time whenever the CPU is busy, it
can share some other resource and this one or actually the idea is that multiple programs
have their own time slots and each program can use their time slots so, that they can
execute this program. So, this is the way the multitasking things can be achieved and in a
time sharing manner.
(Refer Slide Time: 08:42)

Here is an example that we can use to explain how the multitasking it is possible and. So,
say is a basically single task if it is a single task as we see whenever the single task
requires the CPU time it is their and if it requires at the same time some other resources
say suppose input then the CPU is idle. On the other hand, once the input is reading is
complete then the CPU is engaged for some other task one this task is complete then it
may be some other task say some printing and one printing is over another task and so on
so on.

So, what we can see is that CPU is not busy for all the time whenever it is executing a
program if it is a single threaded because of some other resource requirements. So, this
way actually the a performance or efficiency or the throughput of the system is less as
we can see if we execute this way the code is executed only 57 percent where the system
remain idle for 43 percent. So, this is not an efficient way of solving this program.

On the other hand, if we run 2 programs concurrently say P1 and P2 for example,
whenever CPU is idle, at the same time if we can engage the CPU by other program then
whatever the ideal time can be vanished and then CPU can utilize 100 percent utilization.
So, this way the multitasking if it is possible here actually we can give the time sliced P 1
into this time then next this time and this time for the P 1 this time for P 2 and so on. So,
the time can be sliced among the processes. So, this way it is not only for the 2 processes
even multiple processes n number of processes can be time shared and time slice can be
given to each processes. So, that CPU will be busy and then the program all programs
will be executed in the fastest way.

Now, so, this is the idea about the multitasking is a one way of doing multiple threading
actually.

(Refer Slide Time: 10:56)

So, now other than this the multitasking there is one called the multiprocessing. So, it is
basically the idea is same it is also multithreading, but the idea is called multiple
processes can be engaged here. So, if there are say modules m1 to mn so, all these
modules can be assigned to different processors. So, that all the processors can run
concurrently in a parallel manner.

So, this way the program the entire program can be executed in a faster way and there
are many multiprocessing systems are available today, as we know for example, here
Pentium Xeon having the 32 processors you need Athlon X2 MD is a dual core processor
and then there are 4096 processor Cray X1 having so many processor now. So, these are
the high speed competing environment which basically allows to execute a program in a
multi threaded manner.
(Refer Slide Time: 12:05)

Now, so, here is basically the 2 concepts. So, for the multitasking is concerns so, process
and thread. So, basically the entire programs can have the different parts this basically
the process. So, process is basically is a program is an executable form which can be
loaded into the memory and then once the processors are loaded into the memory
operating system can take care the execution of each processes.

And on the other hand there is a concept of threads which basically the idea about that
how a process can execute in the system. So, it is basically it is a thread is basically a
sequential execution of a set of instructions one by one. So, there are multiple thread
means there is a multiple set of sequential execution of a system which can share the data
among them.

So, multiprocessors multiple processes this basically multiple threads we can say and
whenever one ThreadCome into the picture it is basically is a single process with a single
set of execution. So, multiple threads is basically a concurrent execution whereas, a
single thread execution is called the light weight process because it is a on
ThreadActually.

Now, so, we have learn about the multithreading and we can learn that a multithreading
means a concurrent execution. Now let us see how this multithreading is useful to solve
many problems as we are solving nowadays in our own computing system.
(Refer Slide Time: 13:52)

Now, you know whenever you are using the Gmail software or a Google browser. So,
Gmail software is basically loaded into some server is a Google server Gmail server and
you know at the same time the billion of peoples are using the same Gmail server. In
fact, then how this Gmail server processes all the Gmail users actually at the same time.
So, it is basically they the Google server which basically run the Gmail software’s in
their own system they processes all the users in a multiple threaded manner so, this is a
one example of the multiple threading.

As we see from here a user a user can place a request or can browse the Gmail from the
say Firefox, another Internet Explorer, another may be Opera so all the request goes to
the server at the same time so, billion of requests are there, then this server can process
them all the request individual in a multithreaded program. However, a user can think
that this server is dedicated to his service. So, all user can think that I am getting as if the
I am the only soul user in the system, actually the Google server serves multiple users at
the same time and this is possible because of that multithreading concept as it is followed
in execution.
(Refer Slide Time: 15:26)

Now, so, there is idea about this one and then basic purpose of this multi and this is
another example another example of multithreading using multiple processor. So, idea it
is that if so, many users one single server cannot handle then at the end the multiple
server can take care and then they can use it. So, here only 2 server as you see instead of
2 server a large number of servers can take care and then multithreading also can be done
in a multi processing manner also. So, basic idea about that it will not only process
multiple programs in execution, but it reduces overall time of executions for all
programs. So, this is a great advantage that one can achieve using multithreading
manner.
(Refer Slide Time: 16:18)

And this is another example as we see in the context of internet programming. So, the
idea is that if a many users are there in network access the network with different devices
like laptop, mobile phone, PDA, PC personal computer whatever it is there now all the
users those are there in the system they are connected to a server called the proxy server
and then.

So, these proxy server can know that which request to first 2 home in what way so, if so,
there is basically the different other servers those are distributed worldwide and then
from this internet server the request will go and then, they basically possess all the
requested and that again that are the end of the service.

So, another request also come from another network they also process and then they
produce the output and the output go to the again this proxy and then they can again
transmit to this way and this way the multiple execution takes place. So, for the internet
programs are concerns. So, this is a concept of internet programming and internet
programming is today possible because of the concept of multithreading as it is possible.
(Refer Slide Time: 17:47)

So, there are multiple servers that can execute in parallel as we see here for example,
these are internet server and there is basically service request that receives why a server
that needs for to process the different clients and then here as we see this server can run
many threads. So, they are called parallely. So, overall time that is required to get it
serviced will be reduced remarkably and that way we can improve the performance of
the system.

(Refer Slide Time: 18:27)


So, there are many example as we see where the multithreading is there now this is the in
the context of internet related it application now even in our single PC system also we
need the multiple threading. Here for example, the user whenever editing a document at
the same time he can fire a print come on to print one paper. So, to him both the things
editing as well as printing takes place together. So, this is also possible because here the
system can take care 2 threads one editing ThreadAnother is a printing thread. So, is a
pages will be printed one by one it will control the printer buffer and then get the
response and then do it. So, the system which is here can control both the applications
together.

So, this is one example even in the single user in moment also the multithreading is
required in our problem solving.

(Refer Slide Time: 19:26)

And here is another example also. So, for the operating system level is concerned we
also require the multithreading say suppose we are reading something from our hard disk
at the same time we are copying something from our pen drive or floppy disk to hard
disk. So, how this thing is possible again this is possible because of the multithreaded
program. So, they are actually 2 programs one is a writer and the reader, the reader will
read from the floppy hard disk and writer will write in to the hard disk and both things
will takes place together in a multiple threaded manner
So, this ThreadAnd this thread will execute in parallel and in a multithreaded manner
actually. So, there are several applications as we see where the multithreading is must ok.
So, we have learned about why multithreading now this is our turn to learn about how
this multithreading is possible in java. There are many features many concepts are now
available in this context and you will learn all this features one by one in the next few
slides.

(Refer Slide Time: 21:02)

So, here is basically the multithreading is done in the different level, first is the code
level, then medium grain the control level and then fine grain it is a data level and these
way very fine grain the data level it is there. So, here basically in the first code level
multithreading is possible because we have to first decompose the program into different
task where all task can be done independently.

So, at the task level or is a code level is called the code granularity or the task level the
multithreading will start first; that means, you have to when you write the program you
can tell that this is the piece of the code and this is other piece of the code the 2 task they
can do independently and then 2 threads can be planned for that.

One it is there then we can write the threads for each and then the all the threads can be
takes place and then at the execution level it basically creates the process for each thread
is basically the code that is executable for example, in case of your java execution the
byte codes for each threads actually it is there. So, it is a so, for each thread there is a
separate codes that can be placed there and finally, at the CPU level for each code can
takes place in a inter living or in a concurrent manner as it is basically, whether that is a
operating system can manage how this task, this task and this task can be carried out
parallely. So, they can use some process synchronization from time sharing or many
other methods that the operating system can follow for you to execute to more than one
thread together.

So, this is the idea about the parallelism is takes place in this right and java programming
is basically helps us to implement all this concept here, but at it is a very high level
concept. So, we do not have to bother. So, much details which is basically there only we
have to think about this code level and then, this is a that code level if we can plan it; that
means, program level we can say we if we can plan it, then we will be able to achieve the
multithreading. So, java exactly does for these things for us for the programmer.

(Refer Slide Time: 23:37)

Now, so here basically single thread verses multiple ThreadAs we say earlier that this is
the one single thread if it is there one execution, if the multiple thread mean multiple
executions and they can use the common memory common data together actually this is
the idea.
(Refer Slide Time: 23:59)

Now, a therefore, what we learnt is as a summary that, a thread is a piece of code that
runs in a parallel manner with other threads and each thread is a statically ordered
sequence of instruction; that means, each thread is basically one set of a sequential
instruction we can say and all threads are extensively used to express concurrency
whether in a single or multiprocessor machine whatever it is there that mean either in a
time sharing or in a multi processing whatever it is there.

Now, let us see the features which are there so, for the multithreading is concern.

(Refer Slide Time: 24:38)


Mainly 3 things that we have to learn about that, how to create a ThreadAnd how to
schedule the thread so, these are first thing and then second thing is that how the inter
ThreadCommunication can be takes place and finally, the synchronization of this
threads. So, in java there are many what is called the methods are available and there is
again package the package which basically responsible for running multiple threads are
there.

Now the different process that is related to I mean all this task like ThreadCreation,
thread scheduling, thread execution and then inter process ThreadCommunication
synchronization there are few methods which we have mentioned here these are the
methods is basically there.

Now these are the threads execution is done by is basically automatic one manager. So, it
is run time manager we can say the thread manager and this automatically run for you
now an example of a thread which usually occur in whenever you run a java program is
called the garbage collector there is also. So, this garbage collector is basically take the
memory and then how the memory can be efficiently used.

(Refer Slide Time: 26:00)

Now, so, there are many other concepts are there which basically to be considered
whenever we have to schedule the ThreadAnd then control inter process communication
among the different threads and then synchronizations.
Now, for all these activities there is a package which is there in the java jdk called the

java.lang and in the java.lang there is a class ThreadAnd one interface called Runnable.
So, these are the 2 main things that is there in the java and so, for the multithreading
learning is concerned we have to learn this class ThreadAnd interface runnable and using
this ThreadAnd interface runnable we have to learn about how the multithreading is
possible.

(Refer Slide Time: 26:46)

Now, the basic concept about so, for the creating a thread is concerned you write a
program for a thread that is basically the task and then once the thread is ready then you
have to first run the ThreadAnd then before running we have to start this. So, basically it
start and then this so, whenever a thread is build it is basically inactive ThreadAnd if you
can start it the ThreadBecome a alive and from the alive threads run until it terminates
when the thread is terminated the thread is called the dead.

So, doing I mean for controlling, all this start run and everything. So, there is a procedure
which is defined methods which are defines there in the class ThreadAnd in the runnable
interface. So, as you know it is an interface this means the methods are abstract and
public that mean we have to write our own code how to run the ThreadAnd obviously,
how to start it.
(Refer Slide Time: 27:44)

Now, basically the main idea about that if we use a ThreadAs a class which is there and
then your thread should inherit these ThreadClass to build the run method. So, it is
basically we have to override the run method if we use ThreadClass. On the other hand if
we use the runnable interface, then we have to implement the interface using your
ThreadClass and then they are also you have to implement the run method. So, this is the
basic concepts.

Now, we will discuss about using the both how the ThreadCan be created and then how
the ThreadCan be executed. So, let us first start the discussion about how we can create a
thread with the ThreadClass.
(Refer Slide Time: 28:25)

So, idea is very simple we have to extends the java dot lang package ThreadClass and a
ThreadClass can be created.

(Refer Slide Time: 28:39)

And if you use a interface then we have to implement the interface here now here is an
example that we can see how we can create a ThreadAnd what are the methods are there.
So, here basic idea about that this is the class thread extends objects implements runnable
whatever it is there. So, public thread these are the methods these are the constructor I
can say the thread has the constructor in a different form where name of the thread the
interface runnable object can be pass to them and then both name and threads and
everything and they are run into. So, these are the basic structure of the class thread
which is defined in the java dot lang package. So, it is simple not so, very complex
things are there, now we will slowly one learn one by one how all those things can be
handled in our program.

So, this is about the ThreadClass as we see there are constructors and there is a 2
methods run and start and all this 2 methods are as it is basically override because it is
abstract whenever it is there.

(Refer Slide Time: 29:42)

And so, for the different methods are concerned in the ThreadClass other than the this
start and run method also it includes few more methods which we have listed here join
get live, get name, is alive, setting priority, sleep, yield and so, on. So, these are the few
methods are very learning all this methods will basically completes our learning about
the thread execution.
(Refer Slide Time: 30:25)

Now let us first discuss about how we can create our own thread using class thread. So,
this is basically typical steps or procedure that you should follow in your program. So,
here you have to declare a class of your own that is basically your ThreadClass which
should extends the ThreadClass that is there in java dot lang package and then these are
run method we have to override this run method in your program and then once this
ThreadClass is created you can use this ThreadClass to create your own thread.

So, this is your own ThreadAnd this is basically creating a thread objects and then if we
call the start method for this thread object. So, the thread will start it is execution and
then the run will be invoked. So, the run method will be invoked so, that the alive Thread
can execute in the system.
(Refer Slide Time: 31:28)

Now, here is basically the idea about idea about creating the program this is a complete
program that we can see here and as we see this is the one ThreadClass as we have
declared. So, class ThreadA extends this so, ThreadA we create a thread of our own and
this thread, we in this thread we declare the run method of our own you can see the run
method is declared here it is basically there is a loop, loop will roll for i equals to 1 to i
less than equals to 5 (for (i=1;i<=5;i++)) and whenever loop will roll it will print this 1.
So, what we can say that these thread; ThreadA whenever it will run it will print then 5
negative numbers one by one.

On the other hand there is another thread we have created ThreadB, it is similar to this
thread, but here in this run method we define this kind of code it basically run the even
numbers. So, 2 threads as we see we have declared here and once the threads are
declared we can use it. So, these are the 2 threads in addition to these 2 threads there is
one more threads also.
(Refer Slide Time: 32:53)

So, ThreadA and ThreadB that we have discussed in addition to Thread And there is
another ThreadC these basically also the similar run method which we have discussed
here. So, what we can say that we have created 3 threads ThreadA, ThreadB, ThreadC,
creating 3 thread is basically the business about that how we can define the run method;
that means, the how the thread will execute.

I can tell one example suppose if you want to create 2 thread one for sorting program,
another for searching program. So, in the run method you have to implement the sorting
algorithm may be say quick sort and another run method which basically thread for
searching we can implement the binary search algorithm it is a example like this. So, in
the current example we have created 3 threads to print the 3 different types of number
one is negative number, even number and odd number. So, these are the threads creation.

Now, let us see how once the creates threads are created how can utilize in our program.
So, this is basically the main method as we see the main method it is there name under
this class these are main class. Now here we just look this things carefully what we can
do is we create one thread object a of the thread; ThreadA. Similarly B and C are the
thread objects for the 2 different ThreadB and ThreadC namely. So, here we can see 3
different threads objects are created.

Now, so, a dot start and b these are the basically once the thread object is created we can
start execution of this thread. So, here basically to do this thing we have to call the start
method for a b and c. Now at this point what happened is that this is the single thread
that is creating this and then immediately a dot start the on thread for a thread; ThreadA
for b ThreadB and c for ThreadC will be executed. This will print the negative number,
this will print the even number and this will print the odd numbers and then finally,
whenever it will come at the end of this one it will come to this System dot out dot
println and it will print that that multithreading is over. So, this way the thread will
execute in our program.

So, what we have learned is that there are 2 main methods, that is basically more crucial
whenever the thread is there the run by the run method you have to declare that what is
the task that to be accomplished by a Thread and then this start method. So, start method
is already defined here there in the java dot lang dot class. So, just we have to use it to
start the execution of the thread. So, this is the concept about the Thread creation and
then finally, execution of thread ok. So, we have learned about how the Thread can be
created using Thread class and in our next module we will discussed about other way of
running threads and managing the threads.

Thank you very much.


Programming in Java
Prof. Debasis Samanta
Department of Computer Science and Engineering
Indian Institute of Technology, Kharagpur

Lecture – 28
Multithreading – II

So, in the last module related to multithreaded Programming in Java, we have discussed
about the basic concept of Multithreading and then how the thread can be created in Java
program and then how the different threads can be executed in parallel. And in the last
discussion, we have used the class thread to create our thread. Now in this discussion, we
will discussed about how the Thread can be created using the Runnable interface the
procedure is very similar to the Thread class creation only a few minor difference is
there.

(Refer Slide Time: 00:53)

Now, let us first start with how we can create a thread using Runnable interface. As you
know if we want to create our Thread using class Thread so, we have to create a Thread
class which is basically extending the class thread. On the other hand the same
procedure, but here we have to create a Thread class that implements Runnable. Now
implements Runnable means in the Runnable interface the method run method is there
which is the public and abstract method these method needs to be created. So, it is
basically implementation of this run Thread is similar to the implementation of the run
method that is there in the Thread class here.

So, in that case, the Thread class run method they are in if you have to extend Thread
class is overriding, but here the run method is to be implemented. Once this class Thread
class is created by Runnable interface then we can create a Thread object for example,
here T is the Thread objects and when you create the Thread objects you see we use the
Thread class and pass these as a parameter. So, my Thread that you have created a new
my two all object is needed to be a pass. So, this is the only difference that you have to
these.

In other cases, if you use the Thread class so, Thread to new Thread no argument to be
passed. So, the only default constructor will take place, but here in this if you use a
Runnable or implement the Thread class using Runnable interface then that object needs
to be passed here, that is the only difference otherwise everything is same basically. So,
here T dot start is basically to start the execution of this thread. Now it is basically the
same again that this is the run method that we have to define as it is we have defined
there in the creating clays using extension of the Thread class and then T start.

So, both the things are, here again, now let us again repeat the semi same procedure that
we have discussed about in ok. In our last module exam example, we have considered
about 3 threads Thread a, Thread b, Thread c, which basically p negative number, even
number and odd number. The same concept here also we are we will just implement
each, but using Runnable interface so, that we can understand that how the two things are
work for us.
(Refer Slide Time: 03:22)

So, here exactly let see this is the Thread X I have given the name Thread X, in this case,
implements Runnable. So, this is the similar the run code that we have used earlier and
then Thread Y same as Thread b that we have discussed here, but it implements the
Runnable run method here.

(Refer Slide Time: 03:48)

So, ThreadX. ThreadY are declared and then it will implement the Thread Z. So, this is
the Thread Z. So, 3 Thread ThreadX ThreadY and ThreadZs are implemented. So,
created we can say 3 Thread class are created by implementing Runnable interface and
this is the main method as we see here these are the main class and here you can see we
create x y and x and y are the Thread object of this Thread x class. And then Thread is
basically created t 1 bypassing this x because, if we use a Runnable interface that object
needs to be passed as a constructor to call the I mean Thread class actually this is a
constructor that is defined in the Thread class.

So, these ways we can see t 1 t 2 and t 3 as you can see in this case again we can call in
one here actually two-step process but is a single-step process that means we can create
the Thread directly call this these passing these also it is equally applicable here. So,
what we can see here t 1 t 2 and t 3 3 Threads objects are created and one these 3 Thread
objects are created they are ready for execution and these are the basically to start the
Thread we use t 1 dot start t 2 dot start t 3 dot start and then Thread will be run in
parallel. So, this is the multithreading using Runnable interface as we have learned it
here.

So, we can see basically the same thing implements versus extends and then just how to
create the Thread object otherwise for the run and everything the same in both concepts.
So, the two ways of running a multithreading program using extends and Runnable
interface.

So, there is no I mean such a rule that these were these way the search basically the
difference syntax we can say the different procedure how the different Thread can
executes now. So, we have learned about how a Thread can be created although it is a
simple example that we have considered, this is the idea about and then it can be
extended to any type of complex there any number of threads can be executed any
number of threads can be then started to execute.

Now there are many more things are there particularly a Thread can be in a different
state. So, now, we will discuss about what are the different states that a Thread may have
and this is very important because whenever we have to control a very complex program
you should know the different states of a Thread that it may have and then how we can
communicate one Thread to another.
(Refer Slide Time: 06:33)

So, basically the interfaces inter-process communication. Now, so, far a Thread is
concerned it has different states like Thread can be in a new state. So, this mean the
Thread is just created and it is yet to start its execution. So, it is a new Runnable. So,
Thread is basically being execution that means it is about to run and run this is basically
active the Thread is in the execution and blocked somehow Thread need something or
Thread has been stopped or it is slipping so; that means, Thread is in a waiting state it is
called the blocked state and then finally, a Thread can be in a dead state; that means,
when it finished it execution.

So, these are the 5 different states that a Thread can be in this there and there are
different methods by which a Thread can change its state like a new, start, yield, sleep,
wait and notify and other some external events also their scheduler, I O and returning
from run and resume all these things are there.
(Refer Slide Time: 07:51)

Now, let us have a detailed discussion detail account of all these methods which
basically to control the states of a threads are there, now this is a state transition diagram
for a Thread that it may have as we have checked that a Thread can be in a new state. So,
whenever the created and then this Thread can be in a new state this means Thread is not
yet started its execution, but ready to start its execution. Now when the start method is
called then this Thread is basically Runnable but is a Runnable basically gives to the
scheduler it is basically the Java run time manager it basically all the Threads are now
started it but is about to execute or run it.

When the scheduler can call it is basically yield and then time slice is allowed to each
state may be in a time-sharing manner that it will share the different resources CPU all
these things so on. So, this is totally is a paradigm of Java run time manager which we
should not bother about anything, but it is basically working like this one. So, whenever
it is there so, it is running. So, there again once the Thread is running that Thread can be
stopped or can be resumed or it can be terminated or suspense so, it is basically
terminated.

So, once that terminated the Thread will go to the dead state otherwise if the Thread is
waiting for any resources in that it required may be Thread is waiting for some other disk
or memory that it is waiting. So, these are the running to it can go to the waiting state.
So, blocked in a running to waiting state the different methods it is there I O request
sleep, wait, join, suspend these are the methods which can change the state from running
to block state. From the block state it can again Runnable different methods, which are
responsible to move a state from blocked state to Runnable states are here.

So, these are the way that the Thread can change from new to dead state and the different
processes are there. So, this is basically state-run transition diagram says that how the
state of a Thread can change and what are the communicating methods are there to
control the execution of a threads and then Thread can be in a different state.

(Refer Slide Time: 10:02)

So, these are the different methods that we have learned about the start method we have
already used it and then suspend method. Suspend method is not exactly the stopping
stop method means the Thread will be dead but suspend means it will temporarily halt
the execution and then if a Thread is suspended by the calling suspend method it can be
again revoked using resume method.

Now, the resume method is basically when the Thread is in a waiting state or in a
blocked state it can be turned into Runnable state. So, the schedule scheduler can take all
the threads from the Runnable state to assign to the CPU for execution and then the sleep
method is basically by explicitly maintaining that Thread should stop it here wait for
some seconds may be n milliseconds like where the argument is n there. So, sleep means
the Thread will not do anything only the sleep for sometimes and yield method is
basically switching that takes from the context of a Thread from the current Thread to the
next available running Thread that is their Runnable thread. So, it is basically usually this
yield method used by the scheduler to invoke a Thread which is waiting ready for
execution that is there in the Runnable state.

(Refer Slide Time: 11:25)

Now, let us see how the thread's scheduling can be done.

(Refer Slide Time: 11:27)

And Thread scheduling can be done there are actually scheduler through scheduler is
basically responsible for scheduling a Threads; that means, scheduling a Thread means it
basically assign Threads to Java run time manager and is basically determines that which
Threads which are there in a Runnable state can be assigned to the system for execution.

Now, again in the Java system, we can assign the priority low, mean priority, high
priority, max priority like. So, according to the priority scheduler will call revoke a
method Thread from the Runnable state to this one and there are some threads we call
the demo thread. So, demo threads are basically running all the time in the system and
then the scheduler can interact with them so, that they can be executed and then they can
control their execution and they the Thread can be in any other states there.

So, the demo Daemon Thread is basically for the general service whenever suppose you
just insert one disk. So, automatically it detect that disk is there whenever some
interrupts are coming to the daemon Thread will take these are the few examples are
there. Now the program can be terminated whenever all threads are finished its execution
if there is some Thread is yet to be executed the program cannot be terminated and then
we have to do for the force termination by pressing the power button or like this one.

(Refer Slide Time: 12:58)

Anyway so, whenever the scheduling of a Thread is concerned again in the system there
are two type of scheduling called the pre-emptive scheduling and non pre-emptive, non
pre-emptive means one the Thread is in execution if it is a non pre-emptive scheduling it
is followed then this Thread cannot be interrupted until it finish it will start its execution.
So, no it cannot be interrupted whereas, the pre-emptive scheduling means, Thread is in
execution, it can be pre-empted may be either can change its state from running to
waiting for state or sleep or whatever it is there.

(Refer Slide Time: 13:38)

So, it is basically the policy of how you want to control the threads in your execution.
So, this is an idea about the pre-emptive scheduling that it basically. So, whenever the
Thread is in running condition, it will either terminates or it will go wait or ready wait or
ready until it finishes its execution. So, this is the idea about the pre non pre-emptive
scheduling; that means, it will no interaction interruption is allowed in case of non pre-
emptive scheduling is there on the other hand in case of pre-emptive scheduling as we
see.
(Refer Slide Time: 14:23)

As we see the pre-emptive scheduling is basically if there is an interruption occur. So, it


basically not wait it will from the run state to go to the ready state. So, this way pre-
emptive occurs anyway. So, this is the matter of policy that you can implement in your
system and this is the concept of an idea about managing the systems whenever you have
to implement it. So, pre-emptive non pre-emptive the core concept of how you want to
control your process in execution or we can say the Thread in execution.

(Refer Slide Time: 14:56)


Now, let us have an example of how the different methods are there which can be
implied to a Thread whenever it is in execution, this is again a simple method that we
can understand about it and it illustrates how the sleep method will work for you. So,
here is an example we can see we create a Thread class the name of the Thread class is
ThreadExample which basically created using Thread class. So, extends Thread now I
can tell you using implement Runnable also you can do it anyway.

So, here is the run method as you see how we can code the run method then this one it is
basically is a loop for loop and here you see sleep we use the sleep method for this that
mean whenever it executed this for i equal to 0 it will just call the sleep method and it
will sleep for 5000 millisecond. So, 5 seconds like and we put this code into this one
because here there may be an exception occurs that 3 Thread is no more there and then
we want to call this Thread using sleep method. So, this is why it is better to put under
try-catch. So, it is basically interrupted exception if it occurs then it can be caught it and
then handle from the premature termination of the program itself or the robust program
this is basically exception handling concept it is followed there.

Now, as we see. So, this is the run method this run method is just run the Thread and
here the idea is that Thread will for each loop whenever it runs. So, first 5seconds it will
sleep then again 5 second it will sleep and then another 5 seconds it will be sleeping like
this one. So, it is the idea about sleep there and if you print one system statement
system.out.print l n before here and after here that before sleeping first and then after
sleeping first then you can see that. So, the threads are executed in parallel wherever it is
sleeping intermittent way.

So, here is basically the idea about here we can see we have created two Thread
ThreadExample object and then start there so; that means, we run two threads parallelly
and if we run this threads parallelly with their print statement here in our demonstration
we will give a demo how this Thread can execute in a different order and everything. So,
this will give an idea about that the threads are running and invoking the sleep method;
that means, Thread is going to sleep there. So, basically, here the threat Thread that we
have created here we are sending a method to control or just change its state from may be
running to waiting for a state like this one or blocking state whatever it is.
So, this way the sleep method like this sleep method we can use many other methods as
we have discussed in previous slides namely, suspend all these things stop all this things
also we can call it here. So, appropriate code is to be planned for that to have it any way
we will discuss all these things in our demo. So, that how the different methods can be
called and then how their consequence is there.

(Refer Slide Time: 18:20)

Now, so, this is an example again we will discuss the portal execution of this statement
how this state can executed when the sleep condition I want to skip here. So, for the
theoretical it is more aspect. So, far that how it basically run, it in actual programming
environment ok. So, this is a Thread control we can say and these are basically the matter
the concept or the features.
(Refer Slide Time: 18:49)

So, for the inter-process Thread communication is concerns here and this is another
example of again inter-process communication of the Thread as we see and this is a very
interesting problem which usually occurs whenever multiple threads are in the execution
of the concept is called the DataRraces. So, here is basically we create one class called
the DataRrace which extends the Thread class here and here we declare one method run
which uses one static integer variable x there. Now, this method is basically used
interchanging for integer i equal to 0, i less than these are basically. So, many times this
will loop and for each iteration x equal to x plus 1 and x equal to x minus 1 as if this loop
is executed.

So, for every iteration x will be initially if x is 0. So, it is 1 then 0 1 and 0, but
interestingly if you run the Thread this DataRrace Thread and you see it it should in this
according to this one single Thread it will always keep the 0 as a value of x, but here the
thing is that because of this intermittent execution and then what is called data races are
there. So, if we run this Threads for this many loops and you will see it always not give 0
it sometimes keeps 1 sometimes gives 0, this is because of the different Thread whenever
it is execution and it is a static variable.

So, it prints the different situation whatever the values are there in this intermittent
execution. So, this is the idea about and then and it basically calls the data race example
in the Java programming concept. So, this basically says that how the different threads
are in execution that we can check it within this kind of illustration.

(Refer Slide Time: 20:47)

Now, so, these are the different way the Thread can be scheduled our Thread can be
communicated inter-process communication we can say and now next is that a Thread
can be synchronized also. So, the Thread synchronization and before this Thread
synchronization, there is also one concept is called the setting the priority our next
example is basically how the set priority of a thread can be established so, that the
scheduler can schedule the execution or the Thread according to their priority.
(Refer Slide Time: 21:23).

Now, so far the priority of a Thread is concerned there are three different priorities that
can be there in the Thread MIN PRIORITY, NORM PRIORITY and then MAX
PRIORITY. So, they have their global value called 1 5 and 10. So, we can set the priority
of a Thread by calling this method set priority which is defined therein class Thread. So,
if this is the Thread and then we can call this method setPriority and passing the num
number 1 5 or 10, then it will set the priority according to MIN PRIORITY NORM
PRIORITY or MAX PRIORITY, otherwise you can write this one min priority the
global variable declared in the Thread class itself. So, we can use it also.

So, a Thread can be assigned its priority and once it is assigned then the Thread can be
served using some CPU scheduling policy, for example, FCFS First Come First Served
policy look like this one. So, there is the way that the Thread can be there now let us
have an example.
(Refer Slide Time: 22:32)

So, that how this Thread can be priority can be assigned and accordingly the Thread
execution can be controlled. So, here is an example of this. So, here class A we create a
Thread and then run method we define here run method has a loop and this is a loop
control variable i equals to 1 to 4. So, loop will roll for times and each time the loop is
rolled it will print the value of i here; that means, loop variables. So, this is the Thread A
and similarly, this is the class A basically one Thread that we have created, now let us
have some more Thread because multiple Thread execution is more interesting.

(Refer Slide Time: 23:18)


So, here is another example and here is a class B another Thread that you have created
this also similar to the class A Thread, but it just printing the variable the loop variable of
its own. And so, this is the class B and similarly, we can define another class say class C
say another Thread.

(Refer Slide Time: 23:38)

And this is a class C Thread as we see class C Thread and then this also another a run
method it will print the k. Now we can see we have created just for playing only 3
threads by means of 3 classes class A class B and class C they are the from Thread class
the run method is created. Now once these threads are created now it is our turn that how
this main class can be composed. So, that all these three threads can be executed.
(Refer Slide Time: 24:12)

So, here is the main method as we see here this is the main methods and here we see we
have created 3 threads namely threadA threadB and threadC of the class A B and C that
we have discussed.

Now, once the Threads is created here we see we assign the Priority of the 3 threads like
threadC setPriority Thread MAX PRIORITY and then threadB setPriority threadA
getPriority+1, what is a Priority that the threadA Priority is there that by 1. So, this is the
Thread Priority sets and similarly threadB threadA Priority also Thread MIN
PRIORITY. So, these are the different ways the Priority can be set for some different
purposes we have setting this one. So, Thread Priority can be set this way, once the
Priority set we just simply start the execution of this thread and as you see this is
basically starting and start.

Now as you see whenever the threads are started it is not started in this way such this is
the first A will start B will start C will start is not that, if you see the print statement and
then in our demonstration we will see how this program gives the print output then we
will see that here out of these which has the first highest priority. For example, here
threadC has the highest Priority it will be executed first, then we see the threadB is the
next Priority because of threadA the lowest priority.

So, threadB will be executed and then ThreadA and then then the loop will be in an inter
min low a depending on the Priority the different execution will take place. So, this way
the ThreadPriority can be set and then it basically used by the scheduler to schedule the
Thread in its own way

(Refer Slide Time: 26:10)

Now, here is another example of the join method we have discussed, as I told you it is
also considered the con. So, if suppose one Thread cannot begin if the other Threads are
not finished its execution. So, in that case the other Threads switch should be waited for
to begin another Threads that can be controlled using join method here and this is a very
simple example as we see suppose t 1 and t 2 are the Threads are created, then we create
t 1 is a Thread and t 2 is another Thread by means of Thread class somehow created
there and we create by some methods are Runnable interface that means ok.

So, we have to run implement the two-run method by implementing the Runnable
interface that can be passed. So, the t 1 and t 2 the 2 Thread object can be created and
then they can be started its execution by calling t 1 start. So, what the thing is that this 2
Thread will start its execution because of these and then here try-catch there is a t 1 join t
2 join. So, there is a t 1 Thread t 2 Thread and then here t 1 join t 2 join so, it will wait
till all the Threads are finished.

So, then this one then only it will come to this one then it will execute the final
statement. So, join is basically the idea is that if there are many threads are there if we
join. So, all the. So, here the Thread point execution will wait until all threads are
finished its execution come here then the next task will take place there. So, this is the
concept of join is basically communicating or controlling the inter-process threads
actually.

Now, our last topic so, regarding this multithreading is basically synchronization of
threads, now the synchronization of threads in means that if two or more threads enter
into the same process then it may lead to lot of abnormality. So, what we can do is that,
if we use the synchronizations that automatically the Java run time manager will control
their executions say that no 2 Thread should not access the same data or same section
together that is called the critical section actually those are the students from computer
science they probably know that critical section is semaphore implementation.

(Refer Slide Time: 28:38)

So, it is basically synchronization, it is very simple the methods which we want to


synchronize just use the synchronize keyword before them and then synchronization
automatically takes care it is so, easy so, for the implementation is concerned.
(Refer Slide Time: 28:54).

Now, here let us have a very simple example that how the synchronization is there. Now
in banking transaction say suppose one Account where from the 2; one from the ATM
and one from the Bank terminal want to access the same account sometimes, in one
account one transaction one wants to use withdraw and another is to deposit.

Now, if they are not synchronized properly then, in fact, it can leads to a different result.
For example, say suppose in the account balance is 1000 and then once a deposit is 500
and withdraw is 300, if it is not successful then what is the out outcome will be that
either it is ok. So, it is basically the correct output should be 1200 because 500 deposits
and 300 withdraw, but if it is not successful then you may get that output as either 1500
or 700 because of the abnormality the situation is there. This means that both the
execution transaction deposit and withdraw should not take place simultaneously. Once
if it is not finished then others should not be executed like this one.

So, this is the one example that to this one here basically one class Account that is a
normal class which has some members and methods are there basically balance, account
number and displayBalance and whatever it is there is a very simple method are there.
And in this Account we define two methods deposit and withdraw and the deposit is
basically depositing the money. So, balance whatever it is their amount it will be
adjusted and withdraw means it will just this one.
Now, here we can see we use the keywords synchronized here one this means that if the
two methods are called for this class object account then they are basically already called
in a synchronized manner. So, it is right. So, this class is very simple to understand and
then only the thing that you should use the synchronize keyword here now.

So, this is the idea about and here is basically the class transaction we can say the
transaction is basically implementation using a threading example here we can see, we
implement transaction deposit there is two methods two transaction deposit class one is
related deposit and it basically implements Runnable. So, the run method as we declared
here this is basically the Constructor of this class and then run method is basically right
account X dot deposit basically these run method call this deposit method. So, this is the
TransactionDeposit.

(Refer Slide Time: 31:39)

And similarly, the transaction withdraw also another method as we have declared here
transaction withdraw it is a same the Runnable interface and this is a constructor for this
and here is the run method as you see is basically called the withdraw method of these
object account y.

Now, so, the two methods withdraw and deposit being synchronized they are basically
operated for the two operations, nowhere is the methods the main method as we see. So,
so main method this is the main method as we see the transaction is the name of the class
and the main method it is here its basically for the account class we create an object ABC
and then that balance is 1000 and then we call this Thread t 1 TransactionDeposit
TransactionWithdraw these are the two threads are executed in parallel t 1 and t 2 are the
two threads; that means, here we want to say imply that two executions are invoked at
the same time and then if there is no you can run this program with removing
synchronized what will happen.

And if you run this program with synchronizing what will happen you can see readily the
difference, but difference may not be always because the data race example that we have
discussed because of this things it may leads to abnormal results because if it is not there,
but if you synchronize, it always give the correct result all the time.

(Refer Slide Time: 33:08)

So, this is the idea about the synchronized and then again in the stack implementation the
same synchronize also we can used it anyway. So, that stack is basically the
implementation in a data structure that is there. So, I just want to avoid this discussion
here we will discuss this thing when we will discuss about the in our demonstration who
will have more examples and then more execution so, that we can run it.
(Refer Slide Time: 33:38)

And so, this is the synchronization that we can have it and using the synchronized word
that, we can control and then process the Thread execution there.

(Refer Slide Time: 33:42)

So, anyway so, this is about multithreading the concept is very vast and many more
things are to be discussed in detail anyway. So, although we have used the two modules
many more things should be discussed while we will have a quick I mean complete
demonstration on the different aspects of multithreading programming.
So, this is about the multithreading and after multithreading, the next thing is very
important about that how the input and output way program can be handled because Java
is for internet programming and then input and output from the many sources. So, how
Java can manage the different sources of inputs and then so, output also we will discuss
in our next discussion.

Thank you.
Programming in Java
Prof. Debasis Samanta
Department of Computer Science and Engineering
Indian Institute of Technology, Kharagpur

Lecture – 29
Demonstration – XI

So, today we have planned our demonstration based on the lessons that we have learned
in the last 2 modules on multithreading in Java. So, as you know we have discussed
about multithreading concepts and here basically we have discussed about how the
threads can be created and then the process communication among the different threads,
the states of different threads and finally the synchronization aspects.

(Refer Slide Time: 00:35)

So, in today’s demo we will learn everything from the practical point of view, we will
see exactly how ThreadCan be created and then those ThreadCan be executed.

And then we have already discussed that there are 2 ways of creating thread. So, using
ThreadClassAnd Runnable interface. So, we will learn about this the 2 things the 2 ways
of creating the threads and running them and there are different methods to control the
threads. So, there will be sufficient demonstrations on them. So, that we can learn about
what are different methods to control the threads and then for the inter process
communication again, there are few methods we will see exactly how this inter process
communicating methods can be invoked for the threads and then again the ThreadCan be
controlled.

Now finally, we will discussed about one real life example is very small example. So
banking transaction so how the transactions in a bank right for the operation of an
account holder can be managed and that is the using threads itself. So, this is basically by
the process of synchronization. So, we will discuss about this things.

So, let us have the demo on these aspects. So, first we have let us have the demo on how
we can create a thread using ThreadClass.

(Refer Slide Time: 02:15)

So, in this program as we see we see here this program if you see here we have created 3
threads namely here, we have created 3 threads as we see ThreadA and this is basically
extends Thread, this means this basically threads using the class Thread and so creating a
thread means, you have to override the run method and as we see we have overriding the
run method here and this run method is basically as we see from this code this run
method will run for 0 to 5 loops and in each loop it will print the negative number.

So, starting from minus 1, 2, 5 like and next thread. So, it is a ThreadB again it is extend
the Thread ClassAnd here also we override the run method these also loops for 0 to 5 6
times and in this loop as we see these method will print the 6, the first 6 even numbers
and similarly another thread, ThreadC it is also a extension of class Thread and then here
the run method which is basically a simple loop here and then loop will run from k
equals to 1 to k that mean 5 times and here it will print first 5 odd numbers.

Now so these are the 3 threads. So, our plan is to run these 3 threads simultaneously now
here is the main method and in this main method, we see how we can create the 3 3
thread objects A, B and C these are the 3 thread objects for the 3 classes like ThreadA,
ThreadB and ThreadC. Now this is the syntax as you see how we can create the 3 thread
object for the 3 Thread classes that we have defined here. Now in order to run the thread
so we have to call the method start for each thread object for example, a.start() this
means that ThreadA will run b.start() that this will run c.start() this will run.

So here, in this main method as we see so these are the 3 threads we will run, but in
addition to the main method itself is a thread. So, all together here actually 4 thread will
run. So, this is the ThreadA will run this means this thread will print the negative
numbers ThreadB when it will run it will print odd even numbers ThreadC will run when
it will print the odd numbers and here this main thread other than this executing or
invoking this threads, it will also print this statement and we are not sure the which
thread will be executed in which order because here, the scheduler will take all the
threads and depending on it is own because, here no priority has been assigned actually
all threads are in random pattern, it will be executed. Now so this is the program.

Now, we can have some idea about how this program, if it run then how it will give us
the output. So, name of the program and we have given here demonstration_111 ok. So,
this program is now compiled and then we are running this program and yeah as we see
these program, it gives the output here multithreading is over this is basically from the
main Thread and here you see ThreadC ThreadB A B B they are basically in random
order somehow ThreadC which was (Refer Time: 06:05) invoked in the main method
last, but it got executed first and then B A B in inter living manner and we see all thread
when they are executed they are printing their number in that order of course, in the way
the loop will executed.

So, this basically example gives that how the different threads will be executed and that
is the execution of the 3 threads. Now let us have another demo.
(Refer Slide Time: 06:35)

So, in this example we have created 3 threads using class Thread that is the extends
Thread now there is an another way of creating threads and running them using the
Runnable interface. So, this is the program which basically gives us an idea about how
the same problem, which we have implemented using Thread Class can be also
implemented using Runnable interface 112 ok.

(Refer Slide Time: 07:09)

Now so this is the example what we can see here how the Thread can be executed using
Runnable interface. Now let us see we define ThreadX the another thread which
implements Runnable interface. So, implements runnable; that means, we want to create
the thread using Runnable interface.

In Runnable interface there is an abstract method, which is basically run. So here,


basically implementing means we have to override the run method. So, this is the code
that basically implements the run method and this implementation is same as the
ThreadA extends Thread class, in the last example similarly ThreadY is the same version
of ThreadB and this is the implementation of run method for this ThreadX and similarly
this is the implementation of run method for ThreadZ, it basically implementing
Runnable interface.

So, as we see there are 3 threads we have created using Runnable interface. Now let us
see how we can create the. So, these are the basically class declaration for the 3 threads
and now this is a main method, this method is basically creates the 3 threads as we
defined ThreadX ThreadY and Thread Z. Now here, you see first we create a x, it is
basically the object of the class Thread X and then we create a thread of that objects. So,
this basically t1 is the thread object for the class Thread X.

So, to use it using Runnable interface method we have to have this syntax like thread t 1
that mean t1 is a Thread And we pass the Thread class that is the x object, which is
basically implementation Runnable interface actually and then so these basically, create
the thread t1 for the ThreadX likewise, these basically t2 is the thread 2 for the class
object y and thread ThreadY actually and this is the another way short cut method also
we can use.

So, t3 is the thread object new Thread and in this constructor. So, there are different
constructor as we see to create the thread, this is the one constructor where you have to
pass the object of the thread, but here we can pass the constructor directly. So, this is the
another way that the thread object can be the thread object can be created. So, these are
one way of creating (Refer Time: 09:51) actually anyway either these way or these way
you can do whatever it is there.

Now so we have created 3 thread t1, t2 and t3 and now we are in a position to run them.
(Refer Slide Time: 10:03)

So here again, we run t1.start(), t2.start(), t3.start() means 3 threads are now started
invoked for they are running and then this is basically the statement which is basically in
the main statement basically, the same program that we have done using Thread class,
but here only the difference is that we have done the same thing using Runnable interface
and definitely it is basically same program, but implementation is different definitely
they will give the same output. Now let us see the output of this program ok.

(Refer Slide Time: 10:39)


So, this ThreadA s you see X Z Y Z all this things run in an inter living manner, because
whenever the thread is executed they are basically executing parallely, but here in our
display we are our producing the output synchronizing. So, better can be that if we have
the three display unit for each display the different Thread can produce their output then
we can see that how the 3 threads are running independently rather, but here is basically
we are producing the output from the 3 threads on the same input same output screen.
So, that is why we are getting the output in the interleaved manner. So, this is the way of
creating threads, we have learn about we can create threads in 2 ways using the class
Thread and the Runnable interface.

(Refer Slide Time: 11:29)

Now, our next illustration is basically to every threads, whenever it is in execution from
the program point of view we can get have information about the threads by means of
their identity. So, the Id of a Thread can be accessed by a method called the getId, which
is defined in the class Thread in the Java.lang.methods class. Now here, let us see one
example as we see here now. So, these basically this is the name of the class that we are
going to declare is the ThreadId threadId is basically extend Thread always whenever
you have to create Thread class you have to have an extension or either Thread class or
implements Runnable interface that is the basic concept of course,.

Now here, the run method basically thread has it is own abstract run method, but
whenever you have to extend it we have to basically implement override this run method.
Now this run method is very simple here basically it include one print statement which
print the thread dot current thread the; that means, whichever the thread is in execution it
will basically for that Thread and then dot getId means for that thread the Id and it
basically it will give the things that which is a current thread is in execution and
corresponding to that thread, what is the Id will be displayed and print and so this is
basically, under try and catch exception to handle the exceptions if any things occurs
whenever this program is in execution.

Now here is the main method here, we can see in this main method there will be in fact, i
equals to 0 to 8; that means, 9 threads will be executed we are basically running for the
same class ThreadId, but 9 occasions. So, the 9 thread will be executed and here
although we are calling in this way, but whenever these threads are in execution they will
be executed simultaneously in parallel.

So, concurrently so these basically, it creates a thread in each loop and then that thread is
basically executes. So, this actually these way the nine loops will be created 9 threads
will be created and then each thread will be executed. So, this is the basically idea of the
program and in this program as we see the output this program will see you will display
the output whenever is thread is in execution and corresponding to their Id.

(Refer Slide Time: 14:07)

So, as we see here thread that is I1 is running thread I5 is running I4 is running now at
we can see 1 to 9. So, 9 threads are basically in execution. So, this way we can see the
threads are executing in parallel, but it is not sure if we run this program again not
necessarily in the same output will be let us run the same program again as we see
possibly it will give you the different ordering of the execution as we see here in this
case; obviously, in the but here in the last 3 we can see the different ordering. So,
ordering is in fact, provably stick or it is not predictable rather unpredictable ordering
actually anyway. So, this is the idea about as we see is a simple example where the, Id of
the Thread can be can be access whenever a thread is in execution.

Now, our next execution next program basically the same, but using Runnable interface.

(Refer Slide Time: 15:07)

As we have seen in the last program, we have created the Thread class, you have we
have extended the Thread ClassAgain the same program as we see here using the
Runnable interface same code, but only the implement this is a different and here again
as usual. So, this is also different because in order to execute or in order to create a
thread which has been implemented by Runnable interface. So, this is basically the
structure of syntax that we have to follow and then we have to just as in the Thread
class .we have to just invoke the start method for each thread to run it.

So, these will create one object each time the loop will roll and then it basically start
again the same output similar output as in the previous this illustration we will be able to
see it. So, here is basically we are running the program here threaded. So, we can see the
similar kind of output as we can see you can see the bigger screen so, that we can see it
clearly? Yes ok. So, this is the basically output as we see. So, here basically in the
different order as we see this is basically same program same logic, but that logic is
implemented using implement using Runnable interface ok. Now our next illustration to
express, the different states of a Thread and as we know the different control by which
the state of a Thread can be managed.

(Refer Slide Time: 16:51)

For example, there is yield method, stop method, suspend method, resume method, sleep
method, whatever it is there.

Now in this example, we will just see exactly how the sleep method will work for us and
then stop method also we will see yield stop and then sleep these are the 3 methods we
will see how this methods can be invoked for a for a current thread under execution.
Now here, is the code as we see we create ClassA extends Thread and here we again
override the run method it is the simple print statement that from which state these thread
in execution. So, it keeps that start from ThreadA and this is basically the loop here we
see for i equals to 1 i less than 5. So, 1 to 5 this loop will roll and if i equals to 1, the
yield method it will be there. So, then system dot out dot print from ThreadA i plus 1 it
basically, print the value of i.

So, yield method is basically tell that this thread is in execution. Now here again ClassB
extends Thread s you see the similar structure of the program code here in this run
method as well as, but here j equals to 1 to j less than 5, this run method also will loop
will roll for 5 times and here whenever j equals to 2 it basically stop; that means, these
thread will be after the running up to 1 1 and 2 from 2 for the third loop one was it will
basically stop and then stop for sometimes until it will stop means it is totally stop this
means, these thread will no more execute; that means, these loop will although for roll
for 5 times, but it will ultimately work for you only for j equals to 1 only.

Now, here again ClassC this is another thread we have created here similar run method k
equals to 1 to 5 and here we see when k equals to 3 we call the sleep and this sleep is 30
30 1000 millisecond 1000 millisecond means one second like. So, this sleep this thread
will sleep for 1 second; that means, it will roll k equals to 1 k equals to 2, whenever k
equals to 3 for sleep 1 second and then again it will roll for 4 and 5.

(Refer Slide Time: 19:29)

So, these are the 3 Thread classes we have created having their own mechanism and now
we in the main method, we can create the 3 objects of this 3 Thread classes t 1, t 2, t 3
and then we just start their execution here and then finally, one the thread is finished it
basically print that end of the thread execution, but as it is here in this main method
actually in parallel 4 threads will run concurrently. So, this is the idea about 3 threads
here and here is the again output we can see how this program run fine. So, these are
warning we can ignore.

So, as we see the output seen here, here, ok. So, end of execution somehow it is the last
statement, but it is the one main thread somehow it is executed first and then ThreadC,
ThreadB, ThreadB in a random fashion as we see the different threads executed and also
we can see the second thread, ThreadB actually as it is run it is basically stop for thread 1
right for the loop and for the 2 4 6, it is basically running. So, this is the way it is
basically it works for us

Now, let us go to the program here the program which we are discussing. So, what
essentially the multithreading basically it is there. So, as we see each thread has its own
code. Now again for example, say suppose we want to run 2 methods, one method will
be for sorting some array of elements and another method for searching some elements
in a array. So, what we can do is that, we can create a thread for the sorting method
implementation we can create another thread for implementation of searching method.
So, whatever the logic there is to sort some array or elements we can write the code
under the run similarly, whatever the code that is required to search an item in an array
we can put into the run method.

So, this is the way that we can run our own what is called the algorithm the method and
that those algorithm can be executed in parallel. So, parallel execution means that they
will share the system may be in a time sharing basis or in a multi programming basis that
is the part of the operating system. So, operating system; that means, here Java run time
manager will manage the execution of all the threads in parallel. So, this way actually if
we run says sorting and searching one by one. So, this may takes a 5 plus 5 10 seconds.

(Refer Slide Time: 22:07)


But, if you run in parallel it may take 5 seconds both the program will run, but it will the
maximally utilize the CPU resources other resources, those are required in your program
execution can be maximally utilized. So, this is the purpose of the thesis purpose of the
threads execution.

Now, let us have the another example as we have learned the method yield stop and then
sleep likewise there is some other method also like suspend and resume method. So, this
examples basically explain us how the suspend and resume method work for us. So,
suspend method means if you write if you can wait make a c thread wait by calling some
method right then suspend method is basically ok. Any one method is running and you
can call the suspend method that mean this thread will be not permanently stop, it will be
temporarily withheld and the same method can be again revoked if we call the resume
method.

So here is a program, which basically explain that we suspend one method Thread and
then the same Thread can be resumed from the other thread exactly. So, here is the code.
Now here, you can say Thread1, we create 1 Thread and this is a run method is basically
simple it is state that print a print statement that this thread starts running and then here
the sleep method we call here sleep for 10 seconds and then the system dot out print l n
the first thread finish running and then this is the Thread2 and here again the similar kind
of code here is basically thread we call a method suspend and then the 2 threads are here.
So, the threads this whenever the 2 threads are in execution, one thread will sleep for 10
milliseconds another thread will go for suspending.

Now here in the main method, as we see we run the 2 threads first and second namely
here and then start it and then execution. So now, let us have the code for that quickly,
yeah as we just output is little bit bigger so that we can see output (Refer Time: 24:25)
fine.
(Refer Slide Time: 24:27)

Now here again, we see the output as we see these are the thread was in executions. So,
sleep and that is why after ten second this sleep this Thread actually revoked and then it
produces the output like this one.

So, you can see that how the suspend and then the sleep the similarly resume method
also we can call the resume method in the main method after sometime the resume
method can be called so that it can resumed it now. So, this is the different method to
control the thread. So, is basically mechanism the way that different Thread can be
controlled. Now here, we have discussed about a priority can be assigned among the
threads.
(Refer Slide Time: 25:09)

Suppose, while in the execution we can set some priority to the threads as we have
discussed about there are 3 priority min priority, max priority and normal priority.

Now, the thread we can assign priority values to all these threads here now, this program
will explain how we can create 3 threads and among these 3 threads we can assign the
priority. So, ClassA is a 1 thread, this thread has a simple loop i equals to 1 to 5 and then
this is the simple loop execution it will print the 3 5 numbers actually 1 to 5.

Similarly ClassB also similar it will print same numbers 1 to 5 and class C also same. So,
both the threads are basically similar form of executions. Now here as we see in the main
method as we see in the main method, let us look at the main method we created 3
threads t1, t 2, t 2 we create 3 threads t1, t2 and t3 here for the class ThreadA ThreadB
and ThreadC and then here the method set priority which is defined in the class Thread
and then we plus argument as Thread.MAX_PRIORITY, this value is already defined in
the ThreadClass.

So here, basically this basically t 3 has been assigned the maximum priority and as we
see t1 has been assigned the lowest priority and here t 2 the set priority get priority,
whatever the priority of the Thread at present it is basically plus 1. So, it is a random
priority then 3 threads are executed invoked and then finally, the main thread it is there
Now, we will see. So, the order actually whatever it is there or you see the max priority
having the thread t3, it will be executed first. So, scheduler will know from this
information that which threads needs to be executed first. As we see here because, t3
because t3 the ThreadC namely having the highest priority and as we see here basically it
basically invoke first then B and then A and B they are basically random priority based
on and they have been executed. So this way, we can assign the priority to a thread so
that the execution of Thread can be further controlled.

(Refer Slide Time: 27:53)

Now so here is another problem, this is very interesting problem multithreading works
good usually first, but if you are not careful then you may not get the right result, now in
this regard there is a problem. So, for the concurrent program execution is concern it is
called the race problem, the data race problem. Now if you see the code here, now this
code is very simple as we see it declare one integer as a static x and the run method is
basically overriding the class method here and here we see x= x +1 , x =x-1.

Now after the end of the loop if we come here. So, what will be the desired output?
Output will be 0 if x is initialized as 0 is not it, but here we see whenever we run this
program it may not produce the result 0 always this is because, it is an intermittent way
this statement will be executed by the scheduler in a different way and that is why it is
not atomic. So, if rather non atomic the execution. So, whenever we run this main
method I mean run this loop for say here 1000 times and each time not necessarily 0
output will be produce, it can produce non 0 output as well as.

Now, let us see the execution of this program, but in the different instances if we run the
different program, it will produce the different result.

(Refer Slide Time: 29:37)

So, if basically 1000 output has been printed on the screen as we see all 0 0, but here
one is there and if we go little bit also top also as we going here may be that sometimes it
is there. So, these are the, this is not the right output actually we can say the erroneous
output and it may produce 0 time most of the time, but sometimes it can produce the
value 1 because of the data race.
(Refer Slide Time: 30:11)

Now, data race because this is the program those are the thread under execution, they are
not synchronization under synchronization means whenever one thread is in execution
then other threads should not be executed simultaneously having accessing the same
variable here, we have made the static variable basically the different thread takes the
same value on their own execution that is why the data race is coming. Now this is a one
example which can better explain in our real life situation the data race condition.

Now this program, we let us have the discussion on this program then I will explain it is
execution and then the in inherent what is called the point in it. As we see here we first
create a Account, this account has 3 fields balance and account number (accountNo)
with 2 fields are there and one method displayBalance. So, a very simple class
declaration as we declared here. In addition to this these method has one method is called
deposit. So, it basically deposit certain amount here into this account.

So; that means, whenever this method will call the balance whatever the current balance
will be increased by the value of amount. So, this is the code it is there and finally, it will
print the display balance which will declared here. Similarly there is another method that
we have declare here withdraw and it basically once amount will be requested for
withdraw will be deducted from the balance and after the withdraw is over it will
basically display the balance information.
So, these basically a simple one class method this is just regarding an account holder
information; that means, the account holder the name or name is not there account
number is here balance is there and the balance information balance status and if the
account holder wants to do a deposit. So, he will just call this method or he if we want to
withdraw something, you will call this method and this method will be executed there.

Now, here is a question point is that if suppose two customers having the same account
number joint account number may be they want to issue the two method deposit
withdraw or deposit again or withdraw or whatever it is there from the two different
terminals then they will be executed from the server point of view. So, it is basically
executed as a thread. Now again, just like a data race if it is not properly synchronized
then these may leads to the erroneous result say balance is 1000 deposit 500 and
withdraw is 300 the result may be sometimes 1300 or result may be sometime 700 so, is
not total correct.

Now here is basically the remedy, remedy is that if we want to make the two method
synchronized by force then we can create the synchronized keyword. So, once the
synchronized keyword is placed then this deposit and the withdraw will be control in a
synchronization that mean only one operation either deposit or withdraw will be
executed not the two operations can be executed in concurrent in parallely.

Now having these are the class information. Now here is basically two methods, we
declare as a transaction deposit basically in order to access the account having the
transaction here. So, integer amount this is the account that mean which account the user
wants to access and this is basically the code for this one and finally, these transaction
deposit will be executed in parallel. So thread so these basically creating a thread for
accessing this deposit method.

(Refer Slide Time: 34:05)


Now, similarly now, similarly there is a transaction withdraw in the same structure as we
see here it basically create a thread in this case and then this thread will be again can run
concurrently with the transaction deposit. So, these are the two threads in this program.
So now, after the two threads are there, this is the main thread this main thread is
basically execute the 2 threads that we have created here as we see we have created an
account information that mean an account is created this is the account say name of the
account B A B balance is 1000 account number is this one and here actually you see t 1
and t 2 the 2 threads are created.

In this case from the same program, but whenever the distributed (Refer Time: 34:50) is
there these 2 Thread can be executed from the different client and it can pass through the
server you can understand that this is basically the request to the server from the 2 client
that mean execution of 2 thread t 1 and t 2.

Now if these 2 threads are to be executed by the server in concurrent then definitely data
race may occur, but here these Thread are created or called for with depositing 500 and
withdrawing 9 900 and then what will happen it will give always the correct result. So, in
this case 1000 is the balance and after we depositing 500. So, total 1500 then after
withdrawing 900, it basically 600. So, this is the output as we see as we see here. So, 500
is deposited this one 900 withdrawn 600. So, this is the correct result.

Now, I can run the same program, but removing the synchronizations it will run again
just quickly we just, but in some situation may not always it can give erroneous result.
(Refer Slide Time: 35:55)

Now here, we can see yeah so, this is the right output as we see here just bigger. Now
see in the first execution the output was correct, but whereas, these execution the output
was not correct in that sense because, they are not executed in synchronization if the
amount is different you can get the another result also like this one anyway. So, these
basically shows that how the synchronization can help us to synchronize the program ok.

So, we have learned all this topics here and go to the yes fine, but the thing is that this is
just only tip of the iceberg, we said say there are many more things that you can consider
while you have to practice it more programs are there from the website link, which you
have mentioned very beginning, you can follow many more programs, you can access
from there and you can run those things there, if you have any doubt any query you are
feel free to ask us.

Thank you very much.


Programming in Java
Prof. Debasis Samanta
Department of Computer Science and Engineering
Indian Institute of Technology, Kharagpur

Lecture – 30
I – O Stream – I

We have learned about how the input-output is possible in Java program. So, the input-
output that we have learned so, far they are related to standard input and then standard
output. Standard input namely the keyboard and standard output is the display screen.

Now, Java provides many more other than this input-output related to only standard
input and output devices. So, today’s module in today’s module we will discuss about
what are the different input-output mechanism is possible in Java. So, this is particularly
called the input-output streams in Java. Now, again the new term that you are just
listening right now is called the stream.

(Refer Slide Time: 01:15)

So, the idea here is that Java treats any flow of data as a stream. Now, Java streams are
classified into two major categories. They are called the input stream and then output
stream. Now, in order to provide versatility in a programming environment, Java
developer provided say very good package deal with input-output stream. This package
is called java.io. So, java.io can handle many what is called the types of devices for the
source for input as well as many destination devices for the output.
For example, the keyboard, mouse, memory disk, network are the input from where data
can be collected. Similarly, data can be streamed into other devices like display unit,
printer, memory disk, network like this one. So, there are so many devices that are
possible by which the input-output stream can be controlled. As I told you Java provides
the java.io packages to dealing with this input-output mechanism.

(Refer Slide Time: 02:35)

Now, basically, the idea about the input stream and output stream is that, that your
program can have any data streaming from any other sources. So, it is called the input
stream mechanism. On the other hand from your program, you can pump data to some
other source, then this is called the output stream which we have discussed in the figure
in these slides. So, this is a basic concept of the input-output stream, that means from the
program the data will be pushed to some that are the output stream or the program will
read something from the input source.
(Refer Slide Time: 03:21)

Now, the java.io package is meant for this managing input-output stream and it is an
exhaustive package. So now, we will discuss about the basics of what is called the
structure in the java.io packages. Now, all the classes that are there in Java IO packages
java.io rather I should say java.io, all classes can be categorized into two bar categories.
They are called byte stream classes and then character stream classes. This category is
basically divided in case of byte stream classes the data input-output mechanism is
control in the form of a byte whereas, in the case of character stream classes data input-
output mechanism is controlled by means of a stream of characters.

(Refer Slide Time: 04:21)


Now, let us have a quick look at the total different hierarchy of the different packages
different classes which are there in this package. We can say that this is the Java stream
classes. Now, as I told you it can be divided into two broad categories: the byte stream
classes and then character stream classes. In the case of byte stream classes there again
two categories called the input stream classes and then output stream classes. And so, for
the character stream classes is concerned again there are two categories: reader class and
then writer class.

So, these are the so, many classes are there and essentially all these classes are to deal
with the different sources as an input as well as output like memory, file, pipe. Now, a
pipe is basically related to the network channel. Now, let us first discuss each one class
each class individually one by one. So, first let us have a discussion on Java input stream
classes that is there in java.io package. Now, as I told you input stream classes are
basically mean for in reading something from memory or from a file or from a pipe and
as it belongs the byte stream class means, it will read in the form of a byte.

(Refer Slide Time: 05:41)

So, here is basically the total classes those are there in input stream classes as we see a
large number of classes are there. And, all this classes can be mentioned like the
FileInputStream, then PipeInputStream, FilterInputStream, ByteArrayInputStream,
SequenceInputStream, then StringBufferInputStream and ObjectInputStream. Now, here
basically so, many classes belong to input stream class because they are basically to deal
the different input in a different manner. For example, byte array input stream class is
basically how to read data from an array which is stored in memory, it is just an example.

There are so, many classes like and then example again filter input stream class if we
consider there are again many different classes belong to this class hierarchy it is. For
example, DataInputStream, data output, data input stream, BufferedInputStream,
PushbackInputStream etcetera. So, we see that there is a lot of classes and I have just
mentioned only one type it is called the filter input stream. Like likewise byte input
stream there again are the subclasses are there. So, our objective here will be to learn it is
not possible to learn all classes one by one, but at least some classes we can learn which
are most frequently used.

(Refer Slide Time: 07:11)

Now so, input stream classes as I already mentioned that it belongs to the byte stream
classes. This means it is used to read 8-bit bytes and supports a number of input related
methods. And, few methods which I have mentioned here which are very common in any
programming; like say how we can read a byte from an input source, how we can close
an input source, how we can make a position of streaming in an input source. And, it is
skipping ahead into some if we want to read the input one source, not in a sequential
manner rather in a random manner. And, then we can also find a total number of bytes in
stream etcetera. There are many such methods that includes in the input stream classes to
process it.
(Refer Slide Time: 08:03)

And, the methods basically belongs to all classes are overridden method. For example,
the read method that can be used for any say for byte array input stream, we can use the
read array method for that. It is basically the overridden method that, those are there in
each class. So, in general, a read method as we see that read a byte from the input stream.
Now, this is an overridden method read byte b; that means, read an array of bytes into b.
So, it will read and store into a temporary location that is there in the program. And, read
also has another overridden method like byte b int n int m.

So, it is basically reading m bytes starting from n and put into the array say b. Available
is another method it says that whether the input stream currently available or not, skip is
basically for random accessing. So, it is skipping n means, it will skip from the current
location to n bytes ahead and then reset also, reset the reading of location of in the input
stream. Reset means it will start from the beginning and then close basically every
stream has to be as it is open; so, as needs to be closed also. So, these are some standard
methods we will learn all these methods when we will have some more detail
explanations regarding a particular stream class.

Now, here again another example data inputs term is a very popular one stream class and
as we see they are also many methods that can be used. So, basically, the data input
stream belongs to this byte; byte stream classes and it basically has many what is called
the utility. So, it can read as a sort integer, it can read as a floating-point number, it can
read as a read normal integer, it can read at a line ok.

It can read long integer, it can read a character, it can read a Boolean, it can read a read
some data in a UTF format; there are many other formats are there. So, so basically it
basically tells that a data input stream, if we have an in, have an input then, we can read
the data from that input source in a variety of ways. That is why the different methods
have been planned and according to your requirement you can fix that which method you
should invoke in order to read a data.

(Refer Slide Time: 10:35)

And, this is the syntax for example, whenever you declare a read is basically read an
integer return an integer value and like this. So, read byte b we have already discussed
about; so, it read as a byte and store into then temporary array b and like this one. And
so, these are the few methods which will learn while we will have a more detail
discussion on it. And so, the method is for example long skip void long skip are a
parameter is a long integer. And, then it will skip to some location depending on a
parameter values first, mark int is basically, it will mark a particular position in a stream.

And, then reset as I told you it is basically reset the file position, I mean stream position
and Boolean markSupported whether any location stream can be supported or not, it will
return true or false like. So, these are the many methods that are required to control our
input mechanism, those are already defined in the in-stream input stream class. Likewise,
there is a class called the Java output stream classes. If the input stream is to read
something from the input source the output stream is just opposite. It will push the data
into some output destination.

Now, likewise the input stream classes it also belongs to the byte stream classes. These
means that it will write something in the form of a byte and this class has again can
output data into memory. It can output data into a file; it can output data into a network
channel. So, it is same as the input stream, but only the thing is that input is taking and
output is pushing.

(Refer Slide Time: 12:25)

So, output stream classes are therefore, used to write 8-bit bytes and like input stream
classes, it also supports a number of methods. For example, writing a byte into an output
source, output destination, closing the stream, flushing stream and etcetera.
(Refer Slide Time: 12:47)

Now, like the input stream also it has many methods in it. Now, one particular class
belong to this Java OutputStream is called file and then the FilePipeOutputStream,
BufferOutputStream, FilterOutputStream. FilterOutputStream, if we consider there again
varieties DataOutputStream, PushbackOutputStream and like this one. So, it is like this
from different sources mean into a different source, how we can put data into that; so,
that is why it is there. For example, if we consider saying the byte array output stream is
basically telling that how we can put some data into an array in memory. It is an example
like this one.

(Refer Slide Time: 13:33)


So, it is again there are many methods like write method; it basically gives an idea about
how we can write a bite into a stream output stream write byte b. It basically say that an
array of bytes how it can write into an output source, write byte b int n and int m. So, it
basically says that how m bytes from the array b starting from n bytes can be pushed into
an output destination and then close and flush is basically closing an output stream. And,
flush is basically output stream is basically clearing cleaning, it is basically called output
stream usually temporarily buffer. And, then whenever you read whenever you push
something before placing it to an output we need to clean it.

If you do not clean it the previous stream that can be used it can be stored in the their
buffer, that is why it is flushed. And, like the data input stream, there is one class called
the data output stream. It is like the data input stream as it was it can write data into
many forms starting beginning with the bytes actually. So, is writeShort means write a
sorted integer, write Double it basically writes a floating-point number, writeInt,
writeLine.

It is basically written a stream consisting of numbers or characters say together, it is


called the writeLine. Then writeLong is basically writing a long integer, write character
writing a character into the output stream, writeFloat and then WriteBoolean and
writeUTF. So, writing data into UTF format. So, these are the different methods those
are there in the data output stream.

(Refer Slide Time: 15:33)


Now, here is basically syntax that writes is basically return does not anything, this
method it takes a byte b or just simply the byte that needs to be written into the output
stream. It is an overridden method, there are three different overridden method as we see
we which we have mentioned here three overridden method here. And, this is a close
method and this is the syntax of the method void close, void flush that means they do not
return anything just do the work for the output stream.

Now so, these are the byte stream classes we said they are reading as a byte form. Now,
another way of input-output streaming it is called characters stream classes. Now,
likewise there are many different methods that are there and broadly all the character
stream classes can be divided into reader class and writer class. So, the reader class just
like an input stream classes will read some data in the form of a character; from either
memory location, from a file or from a network channel. And, write class is basically the
same as the data output streaming, it basically writes some data into memory or in a file
or it can pass the data into a network channel.

(Refer Slide Time: 16:59)

Now, so these are the two classes and they are mostly in the same manner as this one.
The difference is that the byte classes is basically deal the data in the form of bytes
whereas, the character stream classes deal the data in the form of characters. Now so,
reader stream class as I mentioned that it basically this class is to read characters from
some input sources. And, it is in many ways very similar to InputStream classes. On the
other hand write stream classes writer stream classes basically, write characters into the
output destination targets. It is also in many ways very similar to the OutputStream
classes.

(Refer Slide Time: 17:41)

Now, here is the reader stream classes. So, reading input from some input source in the
form of a character. And, as we see in this figure it can read like a BufferReader, it can
read like a character array reader, it can read like a File Reader. I am reading from a file,
it can read just a StringReader read as a string of characters; it can read as a PipeReader,
FilterReader, PushbackReader. So, there are different o a the reading is possible using
the reader stream classes it is mentioned here.
(Refer Slide Time: 18:23)

Now, here is the one quick summary of the different methods we have mentioned here
and it is just for a piece of information. And, the details and everything is really very
difficult to discuss. As you see here that we have mentioned that, if we want to
accomplish a particular task then which classes that we can consider.

Whether it is basically character stream classes or byte stream classes, as we see say
suppose we can perform an input operation. If we want to do so, it can be done using
both character stream class as well as the byte stream class. As an example as we see
here performing input operation can be done using character read class Reader classes
which are there in character stream classes or InputStream classes that are there in byte
stream classes.

Similarly, if we want to perform a task say buffering input, buffering an input means
storing some data into an into a buffer every what is called the input source, in general,
has their own buffer. For example, a keyboard has its own buffer. So, whenever you are
typing from our keyboard it is initially going to the keyboard buffer and from that
keyboard buffer any program can read, either read as a character or it can read as a bytes.
So, if we want to read as a character, then the class that you should consider
BufferedReader and if we want to read as a byte; so, BufferedInputStream.

This means that if we want to read a buffer then and by means of say BufferedReader
then we have to create an object of the class BufferedReader and then that object has its
method. For example, read method or the different methods as we have mentioned and
you can invoke the method for that object to complete the particular task. So, it is like
this as a particular example, if we want to write writing to a file. So, there is an again
both character stream classes as well as write byte stream classes the method is there.

As we see writing to a file has the FileWriter, if we want to use the character stream
classes and then FileOutputStream if we want to use the byte stream classes like this one.
So, these basically give an idea about if we want to perform, not all I have mentioned
only a few tasks that are very important. These are the different task if we want to
perform then if we want to use a character stream class, then we have to use this one.
And, if we want to use a byte stream class then we have to use this one. So, these are the
just for the information that what are the different methods are there.

But, all these things are not possible to learn in just one module. So, we will follow step
by step methods using each class and then each task rather than, how it can be done. So,
this is the better way so, that we can learn about the input-output stream classes into the
program ok. So, this is basically the topics for today. And, in the our next module we
will discuss about how step by step method to handle the different way of input-output
mechanism using in I O stream concept in Java programming.

Thank you very much.

You might also like