Object Oriented Programming (Java) Lecture Notes Unit 4
Object Oriented Programming (Java) Lecture Notes Unit 4
Object Oriented Programming (Java) Lecture Notes Unit 4
Multithreading
Multithreading in Java is a process of executing multiple threads simultaneously.
A thread is a lightweight sub-process, the smallest unit of processing. Multiprocessing and multithreading, both are
used to achieve multitasking. However, we use multithreading than multiprocessing because threads use a shared
memory area. They don't allocate separate memory area so saves memory, and context-switching between the
threads takes less time than process. Java Multithreading is mostly used in games, animation, etc.
1) It doesn't block the user because threads are independent and you can perform multiple operations at the
same time.
2) You can perform many operations together, so it saves time.
3) Threads are independent, so it doesn't affect other threads if an exception occurs in a single thread.
Multitasking
Multitasking is a process of executing multiple tasks simultaneously. We use multitasking to utilize the CPU.
Multitasking can be achieved in two ways:
∙ Each process has an address in memory. In other words, each process allocates a separate memory area. ∙
A process is heavyweight.
∙ Cost of communication between the process is high.
∙ Switching from one process to another requires some time for saving and loading registers, memory maps,
updating lists, etc.
2) Thread-based Multitasking (Multithreading)
∙ A thread is lightweight.
A thread is a lightweight subprocess, the smallest unit of processing. It is a separate path of execution.
Threads are independent. If there occurs an exception in one thread, it doesn't affect other threads. It uses a
shared memory area.
As shown in the above figure, a thread is executed inside the process. There is context-switching between the
threads. There can be multiple processes inside the OS, and one process can have multiple threads.
Java provides Thread class to achieve thread programming. Thread class provides constructors and methods to
create and perform operations on a thread. Thread class extends Object class and implements Runnable interface.
@Mragank Singhal P a g e | 2
Unit - 4 Lecture Notes (Object Oriented Programming) Java Thread Methods
S.N. Modifier and Type Method Description
@Mragank Singhal P a g e | 3
Unit - 4 Lecture Notes (Object Oriented Programming)
21) static boolean interrupted() It tests whether the current thread has
been interrupted.
22) static int activeCount() It returns the number of active threads in
the current thread's thread group.
24) static boolean holdLock() It returns true if and only if the current
thread holds the monitor lock on the
specified object.
@Mragank Singhal P a g e | 4
Unit - 4 Lecture Notes (Object Oriented Programming)
Life Cycle of a Thread
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 - A thread is in terminated or dead state when its run() method exits.
@Mragank Singhal P a g e | 5
Unit - 4 Lecture Notes (Object Oriented Programming)
Creating Threads
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.
∙ Thread()
∙ Thread(String name)
∙ Thread(Runnable r)
Example
@Mragank Singhal P a g e | 6
Unit - 4 Lecture Notes (Object Oriented Programming) }
catch(Exception e){}
}
}
}
class C extends Thread
{
public void run()
{
for(int i=1; i<=10; i++)
{
System.out.println("Class C: " + i);
try
{
//Thread.sleep(200);
}
catch(Exception e){}
}
}
}
class ThreadDemo
{
public static void main(String ar[])
{
A o1 = new A();
B o2 = new B();
C o3 = new C();
System.out.println("main start");
o1.start();
o2.start();
o3.start();
System.out.println("main end");
}
}
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().
@Mragank Singhal P a g e | 7
Unit - 4 Lecture Notes (Object Oriented Programming)
Example
@Mragank Singhal P a g e | 8
Unit - 4 Lecture Notes (Object Oriented Programming)
class ThreadDemo2
{
public static void main(String ar[])
{
A o1 = new A();
B o2 = new B();
C o3 = new C();
Thread t1 = new Thread(o1);
Thread t2 = new Thread(o2);
Thread t3 = new Thread(o3);
System.out.println("main start");
t1.start();
t2.start();
t3.start();
System.out.println("main end");
}
}
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.
If you declare any method as synchronized, it is known as synchronized method. Synchronized method is used to
lock an object for any shared resource.
When a thread invokes a synchronized method, it automatically acquires the lock for that object and releases it
when the thread completes its task.
@Mragank Singhal P a g e | 9
Unit - 4 Lecture Notes (Object Oriented Programming)
Example
class Sample
{
synchronized void showMsg()
{
System.out.print("Hello, ");
try
{
Thread.sleep(1000);
}
catch(Exception e)
{}
System.out.println("Bye!");
}
}
class SyncDemo
{
public static void main(String
ar[]) {
Sample myObj = new Sample();
Test t1 = new Test(myObj);
Test t2 = new Test(myObj);
Test t3 = new Test(myObj);
}
}
@Mragank Singhal P a g e | 10
Unit - 4 Lecture Notes (Object Oriented Programming)
Synchronized Block in Java
Synchronized block can be used to perform synchronization on any specific resource of the method.
Suppose you have 50 lines of code in your method, but you want to synchronize only 5 lines, you can use
synchronized block.
If you put all the codes of the method in the synchronized block, it will work same as the synchronized
Example
class Sample
{
void showMsg()
{
System.out.print("Hello, ");
try
{
Thread.sleep(1000);
}
catch(Exception e)
{}
System.out.println("Bye!");
}
}
@Mragank Singhal P a g e | 11
Unit - 4 Lecture Notes (Object Oriented Programming)
}
}
}
class SyncDemo
{
public static void main(String ar[])
{
Sample myObj = new Sample();
Test t1 = new Test(myObj);
Test t2 = new Test(myObj);
Test t3 = new Test(myObj);
}
}
Daemon Thread in Java
Daemon thread in java is a service provider thread that provides services to the user thread. Its life depend on the
mercy of user threads i.e. when all the user threads dies, JVM terminates this thread automatically.
There are many java daemon threads running automatically e.g. gc, finalizer etc. You can see all the detail by typing
the jconsole in the command prompt. The jconsole tool provides information about the loaded classes, memory
usage, running threads etc.
o It provides services to user threads for background supporting tasks. It has no role in life than to serve user
threads.
o Its life depends on user threads.
o It is a low priority thread.
The sole purpose of the daemon thread is that it provides services to user thread for background supporting task. If
there is no user thread, why should JVM keep running this thread. That is why JVM terminates the daemon thread
if there is no user thread.
@Mragank Singhal P a g e | 12
Unit - 4 Lecture Notes (Object Oriented Programming)
Methods for Java Daemon thread by Thread class
The java.lang.Thread class provides two methods for java daemon thread.
No. Method Description
Example
class A implements Runnable
{
Thread t;
A()
{
t = new Thread(this);
t.start();
}
@Mragank Singhal P a g e | 13
Unit - 4 Lecture Notes (Object Oriented Programming)
public void run()
{
for(int i=1; i<=10; i++)
{
System.out.println("Class B: " + i);
try
{
Thread.sleep(500);
}
catch(Exception e){}
}
}
}
class ThreadDemo3
{
public static void main(String ar[])
{
System.out.println("main start");
A o1 = new A();
B o2 = new B();
C o3 = new C();
System.out.println("main end");
}
}
@Mragank Singhal P a g e | 14
Unit - 4 Lecture Notes (Object Oriented Programming)
Generic Programming
Generics mean parameterized types. The idea is to allow type (Integer, String, … etc, and user-defined types) to be
a parameter to methods, classes, and interfaces. Using Generics, it is possible to create classes that work with
different data types. An entity such as class, interface, or method that operates on a parameterized type is called a
generic entity.
1) Type-safety: We can hold only a single type of objects in generics. It doesn’t allow storing other objects.
2) Type casting is not required: There is no need to typecast the object.
3) Compile-Time Checking: It is checked at compile time so problem will not occur at runtime. The good
programming strategy says it is far better to handle the problem at compile time than runtime.
class GenDemo
{
public static void main(String ar[])
{
MyGen <Integer> iObj = new MyGen <Integer>(100);
iObj.show();
System.out.println("Integer value: " + iObj.getObj());
MyGen <String> sObj = new MyGen <String> ("Hello. Test String");
sObj.show();
System.out.println("String value: " + sObj.getObj());
@Mragank Singhal P a g e | 15
Unit - 4 Lecture Notes (Object Oriented Programming)
}
}
Here, T is the name of a type parameter. This name is used as a placeholder for the actual type that will be passed to
MyGen when an object is created. Thus, T is used within MyGen whenever the type parameter is needed. Notice
that T is contained within < >. This syntax can be generalized. Whenever a type parameter is being declared, it is
specified within angle brackets. Because MyGen uses a type parameter, MyGen is a generic class, which is also
called a parameterized type.
As explained, T is a placeholder for the actual type that will be specified when a MyGen object is created. Thus, obj
will be an object of the type passed to T. For example, if type String is passed to T, then in that instance, obj will be
of type String.
MyGen(T o) {
obj = o;
}
Notice that its parameter, o, is of type T. This means that the actual type of o is determined by the type passed to T
when a MyGen object is created. Also, because both the parameter o and the member variable obj are of type T,
they will both be of the same actual type when a MyGen object is created.
The type parameter T can also be used to specify the return type of a method, as is the case with the getObj( )
method, shown here:
T getObj() {
return obj;
}
Because obj is also of type T, its type is compatible with the return type specified by
Whenever you want to restrict the type parameter to subtypes of a particular class you can use the bounded type
parameter. If you just specify a type (class) as bounded parameter, only sub types of that particular class are
accepted by the current generic class. These are known as bounded-types in generics in Java.
You can declare a bound parameter just by extending the required class with the type-parameter, within the
angular braces as −
@Mragank Singhal P a g e | 16
Unit - 4 Lecture Notes (Object Oriented Programming)
Example
class BDemo
{
public static void main(String ar[])
{
Integer numbers[] = {1, 2, 3, 4, 5};
AvgSample <Integer> iObj = new AvgSample <Integer>
(numbers); System.out.println("Average: " + iObj.average());
String str[] = {"hello", "ab", "def"};
AvgSample <String> sObj = new AvgSample <String> (str);
System.out.println("Average: " + sObj.average());
}
}
@Mragank Singhal P a g e | 17
Unit - 4 Lecture Notes (Object Oriented Programming)
Restrictions and Limitations
It is not possible to create an instance of a type parameter. For example, consider this class:
Here, it is illegal to attempt to create an instance of T. The reason should be easy to understand: because T does
not exist at run time, how would the compiler know what type of object to create? Remember, erasure removes all
type parameters during the compilation process.
No static member can use a type parameter declared by the enclosing class. For example, all of the static members
of this class are illegal:
class Wrong<T> {
// Wrong, no static variables of type T.
static T ob;
// Wrong, no static method can use T.
static T getob() {
return ob;
}
// Wrong, no static method can access object
// of type T.
static void showob() {
System.out.println(ob);
}
}
@Mragank Singhal P a g e | 18