JAVA MOD 4 NOTES_updated
JAVA MOD 4 NOTES_updated
Multi Threading: Thread Concept,Java Thread Model, The main method, Creating Threads, Thread
Priorities, Synchronization,join
A multithreaded program contains two or moreparts that can run concurrently. Each part of such a program is
called a thread,and each thread defines a separate path of execution. Thus, multithreading is aspecialized form
of multitasking.there are two distinct typesof multitasking: process-based and thread-based. It is important to
understand thedifference between the two. For most readers, process-based multitasking is the morefamiliar
form. A process is, in essence, a program that is executing. Thus, process-basedmultitasking is the feature that
allows your computer to run two or more programsconcurrently. For example, process-based multitasking
enables you to run the Javacompiler at the same time that you are using a text editor. In process-based
multitasking,a program is the smallest unit of code that can be dispatched by the scheduler.In a thread-based
multitasking environment, the thread is the smallest unit ofdispatchable code. This means that a single program
can perform two or more taskssimultaneously. For instance, a text editor can format text at the same time that it
isprinting, as long as these two actions are being performed by two separate threads.Thus, process-based
multitasking deals with the “big picture,” and thread-basedmultitasking handles the details.
A thread can be in one of the five states. According to sun, there is only 4 states in thread life cycle in java new,
runnable, non-runnable and terminated. There is no running state.
But for better understanding the threads, we are explaining it in the 5 states.
The life cycle of the thread in java is controlled by JVM. The java thread states are as follows:
1. New
2. Runnable
3. Running
4. Non-Runnable(Blocked)
5. Terminated
1) New
The thread is in new state if you create an instance of Thread class but before the invocation of start() method.
2) Runnable
The thread is in runnable state after invocation of start() method, but the thread scheduler has not selected
it to be the running thread.
3) Running
The thread is in running state if the thread scheduler has selected it.
4) Non-Runnable(Blocked)
This is the state when the thread is still alive, but is currently not eligible to run.
5) Terminated
Thread Priorities
Java Module-4 Notes
Each thread has its own priority in Java. Thread priority is an absolute integer value. Thread priority decides
only when a thread switches from one running thread to next, called context switching. Priority does increase
the running time of the thread or gives faster execution.
A thread can voluntarily relinquish control: This is done by explicitly yielding,sleeping, or blocking on
pending I/O. In this scenario, all other threads areexamined, and the highest-priority thread that is ready to run
is given the CPU.
A thread can be preempted by a higher-priority thread: In this case, a lower-prioritythread that does not
yield the processor is simply preempted—no matter whatit is doing—by a higher-priority thread. Basically, as
soon as a higher-prioritythread wants to run, it does. This is called preemptive multitasking.
Synchronization
Java supports an asynchronous multithreading, any number of thread can run simultaneously without disturbing
other to access individual resources at different instant of time or shareable resources. But some time it may be
possible that shareable resources are used by at least two threads or more than two threads, one has to write at
the same time, or one has to write and other thread is in the middle of reading it. For such type of situations and
circumstances Java implements synchronization model called monitor. The monitor is considered as a box, in
which only one thread can reside. As a thread enter in monitor, all other threads have to wait until that thread
exits from the monitor. In such a way, a monitor protects the shareable resources used by it being manipulated
by other waiting threads at the same instant of time. Java provides a simple methodology to
implementsynchronization.
Messaging
A program is a collection of more than one thread. Threads can communicate with each other. Java supports
messaging between the threads with lost-cost. It provides methods to all objects for inter-thread
communication. As a thread exits from synchronization state, it notifies all the waiting threads.
Threads in Java
1. By extending Threadclass
2. By implementing Runnableinterface.
Thread class:
Thread class provide constructors and methods to create and perform operations on a thread.Thread class extends
Object class and implements Runnable interface.
o Thread()
o Thread(Stringname)
Java Module-4 Notes
o Thread(Runnabler)
o Thread(Runnable r,Stringname)
Runnable interface:
The Runnable interface should be implemented by any class whose instances are intended to be executed by a
thread. Runnable interface have only one method named run().
1. public void run(): is used to perform action for a thread.
Starting a thread:
start() method of Thread class is used to start a newly created thread. It performs following tasks:
o A new thread starts(with newcallstack).
o The thread moves from New state to the Runnablestate.
o When the thread gets a chance to execute, its target run() method will run.
Output:
thread is running...
System.out.println(Thread.currentThread().getName());
thrconstructort1=newthrconstructor();
t1.start();
System.out.println(t1.getName());
A12 a=newA12();
Thread t=newThread(a);
t.start();
System.out.println(t.getName());
Thread t2=newThread();
System.out.println(t2.getName());
}
The main() is the starting point for JVM to start execution of a Java program. Without the main()
Java Module-4 Notes
method, JVM will not execute the program. The syntax of the main() method is:
public:It is an access specifier. We should use a public keyword before the main() method so that
JVM can identify the execution point of the program. If we use private, protected, and default before
the main() method, it will not be visible to JVM.
static:You can make a method static by using the keyword static. We should call the main() method
without creating an object. Static methods are the method which invokes without creating the objects,
so we do not need any object to call the main() method.
void:In Java, every method has the return type. Void keyword acknowledges the compiler that main()
method does not return any value.
main():It is a default signature which is predefined in the JVM. It is called by JVM to execute a
program line by line and end the execution after completion of this method. We can also overload the
main() method.
String args[]:The main() method also accepts some data from the user. It accepts a group of strings,
which is called a string array. It is used to hold the command line arguments in the form of string
values.
1. main(String args[])
Here, agrs[] is the array name, and it is of String type. It means that it can store a group of string.
Remember, this array can also store a group of numbers but in the form of string only. Values passed
to the main() method is called arguments. These arguments are stored into args[] array, so the name
args[] is generally used for it.
The program will compile, but not run, because JVM will not recognize the main() method. Remember
JVM always looks for the main() method with a string type array as a parameter.
Execution Process
First, JVM executes the static block, then it executes static methods, and then it creates the object
needed by the program. Finally, it executes the instance methods. JVM executes a static block on the
highest priority basis. It means JVM first goes to static block even before it looks for the main()
method in the program.
Java Module-4 Notes
Example
classDemo
{
static //static block
{
System.out.println("Static block");
}
public static void main(String args[]) //static method
{
System.out.println("Static method");
}
}
Output:
S
t
a
t
i
c
b
l
o
c
k
S
t
a
t
i
c
m
e
t
h
o
d
Java Module-4 Notes
We observe that JVM first executes the static block, if it is present in the program. After that it
searches for the main() method. If the main() method is not found, it gives error.
Example
A program that does not have the main() method gives an error at run time.
1. classDemoStaticBlock
2.{
3. Static //static block
4.{
5. System.out.println("Staticblock");
6.}
7. }
Output:
We can also use the different name for the String type array and write it as:
String...args: It allows the method to accept zero or multiple arguments. There should be exactly three
dots between String and array; otherwise, it gives an error.
We can also overload the main() method. We can define any number of main() method in the class, but
the method signature must be different.
Example
classOverloadMain
{
Java Module-4 Notes
Output:
mainmethodinvoked
6
public static int NORM_PRIORITY: This is default priority of a thread if do not explicitly define it.
Value for this is 5.
public static int MAX_PRIORITY: This is maximum priority of a thread. Value for this is 10.
packagelabpgms;
class A1 extends Thread
{
publicvoidrun()
{
for(inti=0;i<5;i++)
System.out.println("Inside run method in class A");
Java Module-4 Notes
}
}
class B1 extends Thread
{
publicvoidrun()
{
for(inti=0;i<5;i++)
System.out.println("Inside run method in class B");
}
}
publicclassthrpriorityextends Thread {
publicvoidrun()
{
for(inti=0;i<5;i++)
System.out.println("Inside run method thrpriority");
}
publicstaticvoid main(String[] args) {
thrpriorityt1 = newthrpriority();
A1 t2=newA1();
B1 t3=newB1();
System.out.println("t1 thread priority : " +t1.getPriority());
System.out.println("t2 thread priority : " +t2.getPriority());
System.out.println("t3 thread priority : " +t3.getPriority());
t1.start();
t2.start();
t3.start();
t2.setPriority(10);
t3.setPriority(5);
t1.setPriority(1);
// Main thread
System.out.println(Thread.currentThread().getName());
System.out.println("Main thread priority : "+
Thread.currentThread().getPriority());
// Main thread priority is set to 10
Thread.currentThread().setPriority(10);
System.out.println("Main thread priority : "+
Thread.currentThread().getPriority());
Java Module-4 Notes
}
OUTPUT:
t1 thread priority : 5
t2 thread priority : 5
t3 thread priority : 5
Inside run method thrpriority
Inside run method thrpriority
Inside run method thrpriority
Inside run method thrpriority
Inside run method thrpriority
Inside run method in class A
Inside run method in class A
Inside run method in class A
t1 thread priority : 5
t2 thread priority : 10
t3 thread priority : 5
main
Main thread priority : 5
Main thread priority : 10
Inside run method in class B
Inside run method in class B
Inside run method in class B
Inside run method in class B
Inside run method in class B
Note:
Thread with highest priority will get execution chance prior to other threads. Suppose there are 3
threads t1, t2 and t3 with priorities 4, 6 and 1. So, thread t2 will execute first based on maximum
priority 6 after that t1 will execute and thent3.
Default priority for main thread is always 5, it can be changed later. Default priority for allother
threads depends on the priority of parentthread.
Example:
// Java program to demonstratethat a child thread
// gets same priority as parent
import java.lang.*;
Synchronization in Java
Synchronization in java is the capability to control the access of multiple threads to any shared resource.
Java Synchronization is better option where we want to allow only one thread to access the shared
resource.
1. To prevent threadinterference.
2. To prevent consistencyproblem.
Types of Synchronization
1. ProcessSynchronization
2. ThreadSynchronization
Thread Synchronization
There are two types of thread synchronization mutual exclusive and inter-thread communication.
1. MutualExclusive
1. Synchronizedmethod.
2. Synchronizedblock.
3. staticsynchronization.
2. Cooperation (Inter-thread communication injava)
Mutual Exclusive
Mutual Exclusive helps keep threads from interfering with one another while sharing data. This can be
done by three ways in java:
1. by synchronizedmethod
2. by synchronizedblock
3. by staticsynchronization
Synchronization is built around an internal entity known as the lock or monitor. Every object has an lock
associatedwithit.Byconvention,athreadthat needsconsistent access toanobject'sfieldshastoacquire the
object's lock before accessing them, and then release the lock when it's done withthem.
In this example, there is no synchronization, so output is inconsistent. Let's see the example:
classTable{
voidprintTable(intn){//method not synchronized
for(inti=1;i<=5;i++){
System.out.println(n*i);
try{
Thread.sleep(400);
}catch(Exception e){System.out.println(e);}
}
}
}
Java Module-4 Notes
}
classMyThread2 extends Thread{
Table t;
MyThread2(Table t){
this.t=t;
}
public void run(){
t.printTable(100);
}
}
classTestSynchronization1{
public static void main(String args[]){
Table obj = new Table();//only one object
MyThread1 t1=new MyThread1(obj);
MyThread2 t2=new MyThread2(obj);
t1.start();
t2.start();
}
}
Output:
5
100
10
200
15
300
20
400
25
500
When a thread invokes a synchronized method, it automatically acquires the lock for that object and
releases it when the thread completes its task.
Java Module-4 Notes
}
}
}
classMyThread2 extends Thread{
Table t;
MyThread2(Table t){
this.t=t;
}
public void run(){
t.printTable(100);
}
}
25
100
200
300
400
500
The sleep() method of Thread class is used to sleep a thread for the specified amount of time.
t1.start();
t2.start();
}
Java Module-4 Notes
Output:
1
1
2
2
3
3
4
4
Java.lang.Thread class provides the join() method which allows one thread to wait until another thread completes
its execution. If t is a Thread object whose thread is currently executing, then t.join() will make sure that t is
terminated before the next instruction is executed by the program.
If there are multiple threads calling the join() methods that means overloading on join allows the programmer to
specify a waiting period. However, as with sleep, join is dependent on the OS for timing, so you should not assume
that join will wait exactly as long as you specify.
Syntax:
publicclassjoinexampleextends Thread{
publicvoidrun(){
for(inti=1;i<20;i++){
System.out.println(Thread.currentThread().getName()
);
System.out.println(i);
}
}
publicstaticvoid main(String args[]){
joinexamplet1=newjoinexample();
joinexamplet2=newjoinexample();
joinexamplet3=newjoinexample();
t1.start();
try
{
}
catch(Exception e)
{
System.out.println(e);
}
t3.start();
try
{
}
catch(Exception e)
{
System.out.println(e);
}
}
}
OUTPUT:
Thread-0
1
Thread-0
2
Thread-0
3
Thread-0
4
Thread-0
5
Thread-1
1
Thread-1
2
Thread-1
3
Thread-1
4
Thread-1
5
Thread-2
1
Thread-2
2
Thread-2
3
Thread-2
4
Thread-2
5
The above output clearly shows that t1 is executed then t2 and then t3.
Java Module-4 Notes
t1.start();
t2.start();
t1.setName("SonooJaiswal");
System.out.println("After changing name of t1:"+t1.getName());
}
}
Output:
N
a
m
e
o
f
t
1
:
T
h
r
e
a
d
-
0
N
a
m
e
o
f
Java Module-4 Notes
The currentThread() method returns a reference to the currently executing thread object.
Syntax:
t1.start();
t2.start();
}
}
Output:
T
h Thread and Current Thread
Naming
r
e
a
d Thread
Naming
-
The 0Thread class provides methods to change and get the name of a thread. By default, each thread has a
name i.e. thread-0, thread-1 and so on. By we can change the name of the thread by using setName()
T The syntax of setName() and getName() methods are given below:
method.
h
r
1. public String getName(): is used to return the name of athread.
e
2.
a public void setName(String name): is used to change the name of athread.
d
-
Example of naming a thread
1
classTestMultiNaming1 extends Thread{
public void run(){
Java Module-4 Notes
System.out.println("running...");
}
public static void main(String args[]){
TestMultiNaming1 t1=new TestMultiNaming1();
TestMultiNaming1 t2=new TestMultiNaming1();
System.out.println("Name of t1:"+t1.getName());
System.out.println("Name of t2:"+t2.getName());
t1.start();
t2.start();
t1.setName("SonooJaiswal");
System.out.println("After changing name of t1:"+t1.getName());
}
}
Output:
Name of t1:Thread-0
Name of t2:Thread-1
id of t1:8
running...
After changeling name of t1:SonooJaiswal
running...
Current Thread
t1.start();
t2.start();
}
}
Output:
Thread-0
Thread-1
Java Module-4 Notes
Using isAlive( ):
finalbooleanisAlive( )The isAlive( ) method returns
true if the thread upon which it is called is still
running.It returns false otherwise.
packagelabpgms;
publicclassisaliveexampleextends Thread{
publicvoidrun()
{
for(inti=1;i<=5;i++){
System.out.println(i);
}
}
Output:
before t1.start() false
after t1.start() true
1
2
3
4
5
Interthread Communication:
Inter-thread communication or Co-operation is all about allowing synchronized threads to
communicate with each other.
o wait()
o notify()
o notifyAll()
Java Module-4 Notes
1) wait() method
Causes current thread to release the lock and wait until either another thread invokes the notify() method
or the notifyAll() method for this object, or a specified amount of time has elapsed.
The current thread must own this object's monitor, so it must be called from the synchronized method
only otherwise it will throw exception.
2) notify() method
Wakes up a single thread that is waiting on this object's monitor. If any threads are waiting on this object,
one of them is chosen to be awakened. The choice is arbitrary and occurs at the discretion of the
implementation. Syntax:
3) notifyAll() method
Wakes up all threads that are waiting on this object's monitor. Syntax:
packagelabpgms;
classThreadBextends Thread {
inttotal;
publicvoidrun() {
for (inti = 0; i< 10; i++)
{
total += i;
}
}
}
publicclassThreadA
{
publicstaticvoid main(String[] args)
{
ThreadBb = newThreadB();
b.start();
System.out.println("Total is: " + b.total);
OUTPUT:
Java Module-4 Notes
Total is: 0
In the above program ,we want to print the total values calculate by ThreadB,
The following program,synchronises the main and ThreadB,giving the updated value
of total as result.
packagelabpgms;
classThreadBextends Thread{
inttotal;
publicvoidrun(){
synchronized(this)
{
for(inti=0; i<5 ; i++)
{
total += i;
notify();
}
}
}}
publicclassintercommunicationexample {
publicstaticvoid main(String[] args){
ThreadBb = newThreadB();
b.start();
synchronized(b)
{
try{
System.out.println("Waiting for b to complete...");
b.wait(); //wait() tells the calling thread to give up the monitor
//and go to sleep until some other thread enters the same monitor
//and calls notify( ).
}
catch(InterruptedExceptione){
e.printStackTrace();
}
System.out.println("Total is: " + b.total);
}
}}
Java Module-4 Notes
OUTPUT:
Solution
The producer is to either go to sleep or discard data if the buffer is full. The next time the consumer removes
an item from the buffer, it notifies the producer, who starts to fill the buffer again. In the same way, the
consumer can go to sleep if it finds the buffer to be empty. The next time the producer puts data into the buffer,
it wakes up the sleeping consumer.
An inadequate solution could result in a deadlock where both processes are waiting to be awakened.
packagelabpgms;
class Q
{
intn;
booleanvalueSet = false;
synchronizedint get()
{
if(!valueSet)
try {
wait();
} catch(InterruptedExceptione) {
System.out.println("InterruptedException caught");
}
System.out.println("Got: " + n);
valueSet = false;
notify();
returnn;
}
synchronizedvoid put(intn) {
if(valueSet)
try {
wait();
} catch(InterruptedExceptione) {
System.out.println("InterruptedException caught");
}
this.n = n;
valueSet = true;
if(n<=5)
Java Module-4 Notes
{
System.out.println("Put: " + n);
notify();
}}
}
class Producer extends Thread
{
Q q;
Producer(Q q) {
this.q = q;
new Thread(this, "Producer").start();
}
publicvoidrun() {
inti = 1;
while(true) {
q.put(i++);
}
}
}
class Consumer extends Thread
{
Q q;
Consumer(Q q) {
this.q = q;
new Thread(this, "Consumer").start();
}
publicvoidrun() {
while(true) {
q.get();
}
}
}
classproducerconsumer {
publicstaticvoid main(String args[]) {
System.out.println("Press Control-C to stop.");
Q q = newQ();
Producer p1=newProducer(q);
Consumer c1=newConsumer(q);
}
}
OUTPUT:
Got: 2
Put: 3
Got: 3
Put: 4
Got: 4
Put: 5
Got: 5
Garbage Collection is process of reclaiming the runtime unused memory automatically. In other words,
it is a way to destroy the unused objects.
To do so, we were using free() function in C language and delete() in C++. But, in java it is performed
automatically. So, java provides better memory management.
o It makes java memory efficient because garbage collector removes the unreferenced objects
from heapmemory.
o It is automatically done by the garbage collector(a part of JVM) so we don't need tomake
extraefforts.
o By nulling thereference
o By assigning a reference toanother
o By anonymous objectetc.
1) By nulling areference:
1. Employee e=newEmployee();
2. e=null;
1. Employee e1=newEmployee();
2. Employee e2=newEmployee();
3. e1=e2;//now the first object referred by e1 is available for garbagecollection
Java Module-4 Notes
finalize() method
The finalize() method is invoked each time before the object is garbage collected. This method can be
used to perform cleanup processing. This method is defined in Object class as:
gc() method
The gc() method is used to invoke the garbage collector to perform cleanup processing. The gc() is
found in System and Runtime classes.
Output:
object is garbage collected
object is garbage collected
Note: Neither finalization nor garbage collection is guaranteed.