Object Oriented Programming (Java) Lecture Notes Unit 4

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 18

Unit - 4 Lecture Notes (Object Oriented Programming)

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.

Advantages of Java Multithreading

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:

∙ Process-based Multitasking (Multiprocessing)

∙ Thread-based Multitasking (Multithreading)

1) Process-based Multitasking (Multiprocessing)

∙ 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)

∙ Threads share the same address space.

∙ A thread is lightweight.

∙ Cost of communication between the thread is low.


@Mragank Singhal P a g e | 1
Unit - 4 Lecture Notes (Object Oriented Programming)
What is Thread in java

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 Thread class

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

1) void start() It is used to start the execution of the


thread.

2) void run() It is used to do an action for a thread.

3) static void sleep() It sleeps a thread for the specified amount


of time.

4) static Thread currentThread() It returns a reference to the currently


executing thread object.

5) void join() It waits for a thread to die.

6) int getPriority() It returns the priority of the thread.

7) void setPriority() It changes the priority of the thread.

8) String getName() It returns the name of the thread.

9) void setName() It changes the name of the thread.

10) long getId() It returns the id of the thread.

11) boolean isAlive() It tests if the thread is alive.

12) static void yield() It causes the currently executing thread


object to pause and allow other threads to
execute temporarily.

13) void suspend() It is used to suspend the thread.

14) void resume() It is used to resume the suspended thread.

15) void stop() It is used to stop the thread.

16) void destroy() It is used to destroy the thread group and


all of its subgroups.

17) boolean isDaemon() It tests if the thread is a daemon thread.

18) void setDaemon() It marks the thread as daemon or user


thread.

19) void interrupt() It interrupts the thread.

20) boolean isinterrupted() It tests whether the thread has been


interrupted.

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

23) void checkAccess() It determines if the currently running


thread has permission to modify the
thread.

24) static boolean holdLock() It returns true if and only if the current
thread holds the monitor lock on the
specified object.

25) static void dumpStack() It is used to print a stack trace of the


current thread to the standard error
stream.

26) StackTraceElement[] getStackTrace() It returns an array of stack trace elements


representing the stack dump of the
thread.

27) static int enumerate() It is used to copy every active thread's


thread group and its subgroup into the
specified array.

28) Thread.State getState() It is used to return the state of the thread.

29) ThreadGroup getThreadGroup() It is used to return the thread group to


which this thread belongs

30) String toString() It is used to return a string representation


of this thread, including the thread's
name, priority, and thread group.

31) void notify() It is used to give the notification for only


one thread which is waiting for a
particular object.

32) void notifyAll() It is used to give the notification to all


waiting threads of a particular 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

There are two ways to create a thread:

1. By extending Thread class

2. By implementing Runnable interface.

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

Commonly used Constructors of Thread class:

∙ Thread()

∙ Thread(String name)

∙ Thread(Runnable r)

∙ Thread(Runnable r,String name)

Example

class A extends Thread


{
public void run()
{
for(int i=1; i<=10; i++)
{
System.out.println("Class A: " + i);
try
{
//Thread.sleep(500);
}
catch(Exception e){}
}
}
}

class B extends Thread


{
public void run()
{
for(int i=1; i<=10; i++)
{
System.out.println("Class B: " + i);
try
{
//Thread.sleep(500);

@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().

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

@Mragank Singhal P a g e | 7
Unit - 4 Lecture Notes (Object Oriented Programming)
Example

class A implements Runnable


{

public void run()


{
for(int i=1; i<=10; i++)
{
System.out.println("Class A: " + i);
try
{
Thread.sleep(500);
}
catch(Exception e){}
}
}
}

class B implements Runnable


{
public void run()
{
for(int i=1; i<=10; i++)
{
System.out.println("Class B: " + i);
try
{
Thread.sleep(500);
}
catch(Exception e){}
}
}
}

class C implements Runnable


{
public void run()
{
for(int i=1; i<=10; i++)
{
System.out.println("Class C: " + i);
try
{
Thread.sleep(200);
}
catch(Exception e){}
}
}
}

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

Why use Synchronization

The synchronization is mainly used to

1. To prevent thread interference.

2. To prevent consistency problem.

Java synchronized method

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 Test extends Thread


{
Sample obj;
Test(Sample o)
{
obj = o;
start();
}
public void run()
{
obj.showMsg();
}
}

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

method. Points to remember for Synchronized block

o Synchronized block is used to lock an object for any shared resource.


o Scope of synchronized block is smaller than the method.
Syntax to use synchronized block

synchronized (object reference expression) {


//code block
}

Example

class Sample
{
void showMsg()
{
System.out.print("Hello, ");
try
{
Thread.sleep(1000);
}
catch(Exception e)
{}
System.out.println("Bye!");
}
}

class Test extends Thread


{
Sample obj;
Test(Sample o)
{
obj = o;
start();
}
public void run()
{
synchronized(obj)
{
obj.showMsg();

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

Points to remember for Daemon Thread in Java

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.

Why JVM terminates the daemon thread if there is no user 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

1) public void setDaemon(boolean is used to mark the current thread as daemon


status) thread or user thread.

2) public boolean isDaemon() is used to check that current is daemon.

Example
class A implements Runnable
{
Thread t;
A()
{
t = new Thread(this);
t.start();
}

public void run()


{
for(int i=1; i<=10; i++)
{
System.out.println("Class A: " + i);
try
{
Thread.sleep(500);
}
catch(Exception e){}
}
}
}

class B implements Runnable


{
Thread t;
B()
{
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 C implements Runnable


{
Thread t;
C()
{
t = new Thread(this);
t.setDaemon(true);
t.start();
}

public void run()


{
for(int i=1; i<=10; i++)
{
System.out.println("Class C: " + i);
try
{
Thread.sleep(1000);
}
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.

Advantage of Java Generics

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.

A Simple Generic Example

class MyGen <T>


{
T obj;
MyGen(T o)
{
obj = o;
}
T getObj()
{
return obj;
}
void show()
{
System.out.println("Type: " + obj.getClass().getName());
}
}

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.

Next, T is used to declare an object called obj, as shown here:

T obj; // declare an object of type T

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.

Now consider Gen’s constructor:

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

getObj( ). Bounded Types

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.

Defining bounded-types for class

You can declare a bound parameter just by extending the required class with the type-parameter, within the
angular braces as −

class class-name <T extends parent-class>

@Mragank Singhal P a g e | 16
Unit - 4 Lecture Notes (Object Oriented Programming)
Example

class AvgSample <T extends Number>


{
T[] arr;
AvgSample(T[] o)
{
arr = o;
}
double average()
{
double sum = 0.0;
for(int i=0; i<arr.length; i++)
sum += arr[i].doubleValue();
return sum / arr.length;
}
}

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

Type Parameters Can’t Be Instantiated

It is not possible to create an instance of a type parameter. For example, consider this class:

// Can't create an instance of T.


class Gen<T> {
T ob;
Gen() {
ob = new T(); // Illegal!!!
}
}

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.

Restrictions on Static Members

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

You might also like