0% found this document useful (0 votes)
22 views41 pages

Java MODULE-5

The document covers Object-Oriented Concepts in Java, focusing on multithreaded programming, including the differences between multiprocessing and multithreading, advantages of multithreading, and thread states. It explains how to create threads using the Runnable interface and by extending the Thread class, along with examples of thread creation and management. Additionally, it discusses thread priorities and methods for checking thread status and waiting for threads to finish execution.

Uploaded by

abcdfgdvdf
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)
22 views41 pages

Java MODULE-5

The document covers Object-Oriented Concepts in Java, focusing on multithreaded programming, including the differences between multiprocessing and multithreading, advantages of multithreading, and thread states. It explains how to create threads using the Runnable interface and by extending the Thread class, along with examples of thread creation and management. Additionally, it discusses thread priorities and methods for checking thread status and waiting for threads to finish execution.

Uploaded by

abcdfgdvdf
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/ 41

Object Oriented Concepts with Java BCS306A

MODULE 5
Syllabus:
• Multithreaded programming
• Enumerations
• Type Wrappers
• Auto Boxing

Multithreading

Difference between Multiprocessing and Multithreading

There are two distinct types of multitasking: Process-based and Thread-based. It is important to
understand the difference between two. The Program in execution is defined as Process. Thus, the process
based multi tasking is the feature that allows your computer to run two or more programs concurrently.
For example we are able to use the java compiler and text editor at the same time. Another example is, we
are able to hear the music and also able to get the print outs from the printer.
In the thread-based multitasking environment, the thread is the smallest unit of dispatchable code.
This means that the single program can contain two or more parts, each part of the program is called,
Thread. For example the text editor can be formatting the text and also printing the text. Although the
Java programs make use of the process-based multi tasking environments, but the process-based multi
tasking is not under the control of java, Where as the thread-based multitasking is under the control of
Java.
Process-Based Multitasking Thread-Based Multitasking
This deals with "Big Picture" This deals with Details
These are Heavyweight tasks These are Lightweight tasks
Inter-process communication is expensive and Inter-Thread communication is inexpensive.
limited
Context switching from one process to another is Context switching is low cost in terms of memory,
costly in terms of memory because they run on the same address space
This is not under the control of Java This is controlled by Java

Advantage of the Multithreading


 It enables you to write very efficient programs that maximizes the CPU utilization and reduces
the idle time.
 Most I/O devices such as network ports, disk drives or the keyboard are much slower than CPU
 A program will spend much of it time just send and receive the information to or from the
devices, which in turn wastes the CPU valuable time.
 By using the multithreading, your program can perform another task during this idle time.
 For example, while one part of the program is sending a file over the internet, another part can
read the input from the keyboard, while other part can buffer the next block to send.
 It is possible to run two or more threads in multiprocessor or multi core systems
simultaneously.

Dept.of ISE,RNSIT Page 1


Object Oriented Concepts with Java BCS306A

The States of the Thread


A thread can be in one of the several states. In general terms, a thread can running. It can be
ready to run as soon as it gets the CPU time. A running thread can be suspended, which is a temporary
halt to its execution. It can later be resumed. A thread can be blocked when waiting for the resource. A
thread can be terminated.

Single Threaded Program


A Thread is similar to simple program that contains single flow of control. It has beginning, body,
and ending. The statements in the body are executed in sequence.
For example:
class ABC //Begining

//Body

} //ending

Multithreaded Program
A unique property of the java is that it supports the multithreading. Java enables us the multiple
flows of control in developing the program. Each separate flow of control is thought as tiny program
known as "thread" that runs in parallel with other threads. In the following example when the main
thread is executing, it may call thread A, as the Thread A is in execution again a call is mad for Thread
B. Now the processor is switched from Thread A to Thread B. After the task is finished the flow of
control comes back to the Thread A. The ability of the language that supports multiple threads is called
"Concurrency". Since threads in the java are small sub programs of the main program and share the
same address space, they are called "light weight processes".

Main
thread

Start
Start
Start
switch
Thread A
Thread B switch Thread C
Dept.of ISE,RNSIT Page 2
Object Oriented Concepts with Java BCS306A

The Main Thread


When a Java program starts up, one thread begins running immediately. This is usually called the main
thread of your program, because it is the one that is executed when your program begins. The main thread
is important for two reasons:
• It is the thread from which other “child” threads will be spawned.
• Often, it must be the last thread to finish execution because it performs various
shutdown actions.
Although the main thread is created automatically when your program is started, it can be controlled
through a Thread object. To do so, you must obtain a reference to it by calling the method
currentThread( ), which is a public static member of Thread. Its general form is shown here:

static Thread.currentThread( )

This method returns a reference to the thread in which it is called. Once you have a referenceto the
main thread, you can control it just like any other thread.
Let’s begin by reviewing the following example:
CurrentThreadDemo.java
// Controlling the main
Thread. class
CurrentThreadDemo
{
public static void main(String args[])
{
Thread t = Thread.currentThread();
System.out.println("Current thread: " +
t);
// change the name of the thread
t.setName("My Thread");
System.out.println("After name change: " +
t); try
{
for(int n = 5; n > 0; n--)
{
System.out.println(n)
; Thread.sleep(1000);
}
}
Dept.of ISE,RNSIT Page 3
Object Oriented Concepts with Java BCS306A
catch (InterruptedException e)
{
System.out.println("Main thread interrupted");
}
}
}
Output

Dept.of ISE,RNSIT Page 4


Object Oriented Concepts with Java BCS306A

Creation of Thread
Creating the threads in the Java is simple. The threads can be implemented in the form of object
that contains a method "run()". The "run()" method is the heart and soul of any thread. It makes up the
entire body of the thread and is the only method in which the thread behavior can be implemented.
There are two ways to create thread.
1. Declare a class that implements the Runnable interface which contains the run() method .
2. Declare a class that extends the Thread class and override the run() method.
1. Implementing the Runnable Interface
The Runnable interface contains the run() method that is required for implementing the threadsin
our program. To do this we must perform the following steps:
I. Declare a class as implementing the Runnable interface
II. Implement the run() method
III. Create a Thread by defining an object that is instantiated from this "runnable" class as the target
of the thread
IV. Call the thread's start() method to run the thread.

Example program:
Runnable.java
class x implements Runnable
{ //1 STEP
public void run()
{ //2 STEP

for(int i=0;i<=5;i++)
System.out.println("The Thread x is:"+i);
System.out.println("End of the Thread x");
}
}
class RunnableTest
{
public static void main(String args[])
{
x r=new x();
Thread threadx=new Thread(r);
threadx.start();
System.out.println("The end of the main thread");

Dept.of ISE,RNSIT Page 5


Object Oriented Concepts with Java BCS306A
}
}
Output:

2. Extending the thread class


We can make our thread by extending the Thread class of java.lang.Thread class. This gives us
access to all the methods of the Thread. It includes the following steps:
I. Declare the class as Extending the Thread class.
II. Override the "run()" method that is responsible for running the thread.
III. Create a thread and call the "start()" method to instantiate the Thread Execution.
Declaring the class
TheThread class can be declared as follows:
class MyThread extends Thread
{

Overriding the method run()


The run() is the method of the Thread. We can override this as follows:
public void run()
{

}
Starting the new Thread
To actually to create and run an instance of the thread class, we must write the following:

MyThread a=new MyThread(); // creating the Thread


a.start(); // Starting the Thread

Dept.of ISE,RNSIT Page 6


Object Oriented Concepts with Java BCS306A

Example program:
ThreadTest.java
import java.io.*;
import java.lang.*;

class A extends Thread


{
public void run()
{
for(int i=1;i<=5;i++)
{
System.out.println("From Threaad A :i="+i);
}
System.out.println("Exit from Thread A");
}
}

class B extends Thread


{
public void run()
{
for(int j=1;j<=5;j++)
{
System.out.println("From Threaad B :j="+j);
}
System.out.println("Exit from Thread B");
}
}
class C extends Thread
{
public void run()
{
for(int k=1;k<=5;k++)
{
System.out.println("From Threaad C :k="+k);
}
System.out.println("Exit from Thread C");
}
}
class ThreadTest
{
public static void main(String args[])
{
System.out.println("main thread started");
A a=new A();
a.start();
B b=new B();

Dept.of ISE,RNSIT Page 7


Object Oriented Concepts with Java BCS306A
b.start();
C c=new
C();c.start();
System.out.println("main thread ended");
}
}

output: First Run

Second Run: Produces different out put in the second run, because of the processor switching from one
thread to other.

Dept.of ISE,RNSIT Page 8


Object Oriented Concepts with Java BCS306A

Creating Multiple Threads


So far, you have been using only two threads: the main thread and one child thread. However,your
program can spawn as many threads as it needs. For example, the following program creates three
child threads:

// Create multiple threads.

class NewThread implements Runnable


{
String name; // name of thread
Thread t;
NewThread(String threadname)
{
name = threadname;
t = new Thread(this, name);
System.out.println("New thread: " + t);
t.start(); // Start the thread
}
// This is the entry point for thread.
public void run()
{
try
{
for(int i = 5; i > 0; i--)
{
Dept.of ISE,RNSIT Page 9
Object Oriented Concepts with Java BCS306A
System.out.println(name + ": " + i);
Thread.sleep(1000);
}
} catch (InterruptedException e)
{
System.out.println(name + "Interrupted");
}
System.out.println(name + " exiting.");

} //end of run method


} //end of NewThread
class MultiThreadDemo
{
public static void main(String args[])
{
new NewThread("One"); // start threads
new NewThread("Two");
new NewThread("Three");
try
{
// wait for other threads to end
Thread.sleep(10000);
}
catch (InterruptedException e)
{
System.out.println("Main thread Interrupted");
}
System.out.println("Main thread exiting.");
}}

When a Thread is ended

It is often very important to know which thread is ended. This helps to prevent the main from
terminating before the child Thread is terminating. To address this problem "Thread" class provides
two methods: 1) Thread.isAlive() 2) Thread.join().

The general form of the "isAlive()" method is as follows:

final boolean isAlive();

This method returns the either "TRUE" or "FALSE" . It returns "TRUE" if the thread is alive,returns
"FALSE" otherwise.
While isAlive( ) is occasionally useful, the method that you will more commonly use to wait fora thread
to finish is called join( ), shown here:

final void join( ) throws InterruptedException

Dept.of ISE,RNSIT Page 10


Object Oriented Concepts with Java BCS306A
This method waits until the thread on which it is called terminates. Its name comes from theconcept
of the calling thread waiting until the specified thread joins it. Additional forms of join(
) allow you to specify a maximum amount of time that you want to wait for the specified threadto
terminate.

Example Program:

// Using join() to wait for threads to finish.


class NewThread implements Runnable
{
String name; // name of thread
Thread t;
NewThread(String threadname)
{
name = threadname;
t = new Thread( name);
System.out.println("New thread: " + t.getName());
t.start(); // Start the thread
}
// This is the entry point for thread.
public void run()
{
try
{
for(int i = 5; i > 0; i--)
{
System.out.println(name + ": " + i);
Thread.sleep(1000);
}
}
catch (InterruptedException e)
{
System.out.println(name + " interrupted.");
}
System.out.println(name + " exiting.");
}
}

class DemoJoin
{
public static void main(String args[])
{
NewThread ob1 = new NewThread("One");
NewThread ob2 = new NewThread("Two");
NewThread ob3 = new NewThread("Three");
System.out.println("Thread One is alive: "+ ob1.t.isAlive());
System.out.println("Thread Two is alive: " + ob2.t.isAlive());
System.out.println("Thread Three is alive: " + ob3.t.isAlive());

Dept.of ISE,RNSIT Page 11


Object Oriented Concepts with Java BCS306A
// wait for threads to finish
try {
System.out.println("Waiting for threads to finish.");
ob1.t.join();
ob2.t.join();
ob3.t.join();
}
catch (InterruptedException e)
{
System.out.println("Main thread Interrupted");
}
System.out.println("Thread One is alive: "+ ob1.t.isAlive());
System.out.println("Thread Two is alive: "+ ob2.t.isAlive());
System.out.println("Thread Three is alive: "+ ob3.t.isAlive());
System.out.println("Main thread exiting.");
}
}

The Thread Priorities


Thread priorities are used by the thread scheduler to decide when and which thread should be allowed to
run. In theory, higher-priority threads get more CPU time than lower-priority threads. In practice, the
amount of CPU time that a thread gets often depends on several factors besides its priority. (For example,
how an operating system implements multitasking can affect the relative availability of CPU time.) A
higher-priority thread can also preempt a lower-priority one. For instance, when a lower-priority thread is
running and a higher-priority thread resumes (from sleeping or waiting on I/O, for example), it will
preempt the lower priority thread.

To set a thread’s priority, use the setPriority( ) method, which is a member of Thread.This is
its general form:

final void setPriority(int level)

Here, level specifies the new priority setting for the calling thread. The value of level must be within the
range MIN_PRIORITY and MAX_PRIORITY. Currently, these values are 1 and 10, respectively. To
return a thread to default priority, specify NORM_PRIORITY, which is currently 5. These priorities are
defined as static final variables within Thread.

Dept.of ISE,RNSIT Page 12


Object Oriented Concepts with Java BCS306A

You can obtain the current priority setting by calling the getPriority( ) method of Thread,
shown here:

final int getPriority( )

Example Program:

//setting the priorities for thethread


class PThread1 extends Thread
{
public void run()
{
System.out.println(" Child 1 is started");
}
}
class PThread2 extends Thread
{
public void run()
{
System.out.println(" Child 2 is started");
}
}
class PThread3 extends Thread
{
public void run()
{
System.out.println(" Child 3 is started");
}
}

class PTest
{
public static void main(String args[])
{
//setting the priorities to the thread using the setPriority() method
PThread1 pt1=new PThread1();
pt1.setPriority(1); PThread2 pt2=new
PThread2(); pt2.setPriority(9);
PThread3 pt3=new PThread3();
pt3.setPriority(6);
pt1.start();
pt2.start();
pt3.start();
//getting the priority

Dept.of ISE,RNSIT Page 13


Object Oriented Concepts with Java BCS306A

System.out.println("The pt1 thread priority is :"+pt1.getPriority());


}
}

Synchronization
When two or more threads need access to a shared resource, they need some way to ensure that
the resource will be used by only one thread at a time. The process by which this is achieved is called
synchronization.

Key to synchronization is the concept of the monitor (also called a semaphore). A monitor is an
object that is used as a mutually exclusive lock, or mutex. Only one thread can own a monitor at a given
time. When a thread acquires a lock, it is said to have entered the monitor. All other threads attempting to
enter the locked monitor will be suspended until the first thread exits the monitor. These other threads are
said to be waiting for the monitor. A thread that owns a monitor can reenter the same monitor if it so
desires.

Let us try to understand the problem without synchronization. Here, in the following example to threads
are accessing the same resource (object) to print the Table. The Table class contains one method,
printTable(int ), which actually prints the table. We are creating two Threads, Thread1 and Thread2,
which are using the same instance of the Table Resource (object), to print the table. When one thread is
using the resource, no other thread is allowed to access the same resource Table to print the table.

Example without the synchronization:


Class Table
{

void printTable(int n)
{ //method not synchronized
for(int i=1;i<=5;i++)
{
System.out.println(n*i);
try{
Thread.sleep(400);
}
catch(InterruptedException ie)
{
System.out.println("The Exception is :"+ie);
}
}
} //end of the printTable() method
}

class MyThread1 extends Thread


{
Table t;

Dept.of ISE,RNSIT Page 14


Object Oriented Concepts with Java BCS306A

MyThread1(Table t)
{
this.t=t;
}
public void run()
{
t.printTable(5);
}
} //end of the Thread1

class MyThread2 extends Thread


{
Table t;
MyThread2(Table t)
{
this.t=t;
}
public void run()
{
t.printTable(100);
}
} //end of Thread2

class TestSynchronization1
{
public static void main(String args[])
{
Table obj = new Table();//only one objectMyThread1
t1=new MyThread1(obj); MyThread2 t2=new
MyThread2(obj); t1.start();
t2.start();
}
}
The output for the above program will be as follow:
Output: 5
100
10
200
15
300
20
400
25
500
In the above output, it can be observed that both the threads are simultaneously accessing the Table object
to print the table. Thread1 prints one line and goes to sleep, 400 milliseconds, and Thread1 prints its task.

Dept.of ISE,RNSIT Page 15


Object Oriented Concepts with Java BCS306A

Using the 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.
The general form of the synchronized method is:
synchronized type method_name(para_list)
{
//body of the method
}
where synchronized is the keyword, method contains the type, and method_name represents thename of
the method, and para_list indicate the list of the parameters.

Example using the synchronized method

Class Table
{

synchronized void printTable(int n)


{ //method not synchronized
for(int i=1;i<=5;i++)
{
System.out.println(n*i);
try{
Thread.sleep(400);
}
catch(InterruptedException ie)

System.out.println("The Exception is :"+ie);


}
}
} //end of the printTable() method
}

class MyThread1 extends Thread


{
Table t;
MyThread1(Table t)
{
this.t=t;
}
public void run()
{
t.printTable(5);
}
} //end of the Thread1

Dept.of ISE,RNSIT Page 16


Object Oriented Concepts with Java BCS306A
class MyThread2 extends Thread
{
Table t;
MyThread2(Table t)
{
this.t=t;
}
public void run()
{
t.printTable(100);
}
} //end of Thread2

class TestSynchronization1
{
public static void main(String args[])
{
Table obj = new Table();//only one objectMyThread1
t1=new MyThread1(obj); MyThread2 t2=new
MyThread2(obj); t1.start();
t2.start();
}
}
Output: 5
10
15
20
25
100
200
300
400
500

In the above output it can be observed that when Thread1 is accessing the Table object, Thread2 is not allowed to
access it. Thread1 preempts the Thread2 from accessing the printTable() method.

Note:
1. This way of communications between the threads competing for same resource is
called implicit communication.
2. This has one disadvantage due to polling. The polling wastes the CPU time. To save
the CPU time, it is preferred to go to the inter-thread communication.

Dept.of ISE,RNSIT Page 17


Object Oriented Concepts with Java BCS306A

Inter-Thread Communication
If two or more Threads are communicating with each other, it is called "inter thread" communication.
Using the synchronized method, two or more threads can communicate indirectly. Through, synchronized
method, each thread always competes for the resource. This way of competing is called polling. The
polling wastes the much of the CPU valuable time. The better solution to this problem is, just notify other
threads for the resource, when the current thread has finished its task. This is explicit communication
between the threads.

Java addresses this polling problem, using via wait(), notify(), and notifyAll() methods. These
methods are implemented as final methods in Object, so all classes have them. All three
methods can be called only from within a synchronized context.

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( ).
notify( ) wakes up a thread that called wait( ) on the same object.
notifyAll( ) wakes up all the threads that called wait( ) on the same object. One of
the threads will be granted access.

These methods are declared within Object, as shown here:

final void wait( ) throws InterruptedException


final void notify( )
final void notifyAll( )
Additional forms of wait( ) exist that allow you to specify a period of time to wait.

Although wait( ) normally waits until notify( ) or notifyAll( ) is called, there is a possibility that
in very rare cases the waiting thread could be awakened due to a spurious wakeup. In this case, a waiting
thread resumes without notify( ) or notifyAll( ) having been called. (In essence, the thread resumes for no
apparent reason.) Because of this remote possibility, Sun recommends that calls to wait( ) should take
place within a loop that checks the condition on which the thread is waiting. The following example shows
this technique.

Example program for producer and consumer problemclass Q


{
int n;
boolean valueSet = false;
synchronized int get()
{
while(!valueSet)
try {
wait();

Dept.of ISE,RNSIT Page 18


Object Oriented Concepts with Java BCS306A
}
catch(InterruptedException e)
{

Dept.of ISE,RNSIT Page 19


Object Oriented Concepts with Java BCS306A
System.out.println("InterruptedException caught");
}
System.out.println("Got: " + n);
valueSet = false;
notify();
return n;

} //end of the get() method


synchronized void put(int n)
{
while(valueSet)
try {
wait();
}
catch(InterruptedException e)
{
System.out.println("InterruptedException caught");
}
this.n = n; valueSet = true;
System.out.println("Put: " + n);
notify();

} //end of the put method


} //end of the class Q

class Producer implements Runnable


{
Q q;
Producer(Q q)
{
this.q = q;
new Thread(this, "Producer").start();
}
public void run()
{
int i = 0;
while(true)
{
q.put(i++);
}
}
} //end of Producer
class Consumer implements Runnable
{
Q q;
Consumer(Q q)
{

Dept.of ISE,RNSIT Page 20


Object Oriented Concepts with Java BCS306A

this.q = q;
new Thread(this, "Consumer").start();
}
public void run()
{
while(true)
{
q.get();
}
}
}//end of Consumer

class PCFixed
{
public static void main(String args[])
{
Q q = new Q(); new
Producer(q); new
Consumer(q);
System.out.println("Press Control-C to stop.");
}
}

Suspending, Blocking and Stopping Threads


Whenever we want stop a thread we can stop from running using "stop()" method of thread
class. It's general form will be as follows:
Thread.stop();
This method causes a thread to move from running to dead state. A thread will also move to
dead state automatically when it reaches the end of its method.
Blocking Thread
A thread can be temporarily suspended or blocked from entering into the runnable and runningstate
by using the following methods:
sleep() —blocked for specified time
suspend() ----blocked until further orders
wait() --blocked until certain condition occurs
These methods cause the thread to go into the blocked state. The thread will return to the
runnable state when the specified time is elapsed in the case of sleep(), the resume() method is invoked in
the case of suspend(), and the notify() method is called in the case of wait().

Example program:
The following program demonstrates these methods:
// Using suspend() and resume().

class NewThread implements Runnable

Dept.of ISE,RNSIT Page 21


Object Oriented Concepts with Java BCS306A

{
String name; // name of thread
Thread t;
NewThread(String threadname) {
name = threadname;
t = new Thread(this, name);
System.out.println("New thread: " + t);
t.start(); // Start the thread
}
// This is the entry point for thread.
public void run()
{
try
{
for(int i = 15; i > 0; i--)
{
System.out.println(name + ": " + i);
Thread.sleep(200);
}
}
catch (InterruptedException e)
{
System.out.println(name + " interrupted.");
}
System.out.println(name + " exiting.");
}
}
class SuspendResume
{
public static void main(String args[])
{
NewThread ob1 = new NewThread("One");
NewThread ob2 = new NewThread("Two");try
{
Thread.sleep(1000); ob1.t.suspend();
System.out.println("Suspending thread One");
Thread.sleep(1000);
ob1.t.resume(); System.out.println("Resuming
thread One"); ob2.t.suspend();
System.out.println("Suspending thread Two");
Thread.sleep(1000);
ob2.t.resume(); System.out.println("Resuming
thread Two");

Dept.of ISE,RNSIT Page 22


Object Oriented Concepts with Java BCS306A

}
catch (InterruptedException e)
{
System.out.println("Main thread Interrupted");
}
// wait for threads to finish
try
{
System.out.println("Waiting for threads to finish.");
ob1.t.join();
ob2.t.join();
}
catch (InterruptedException e)
{
System.out.println("Main thread Interrupted");
}
System.out.println("Main thread exiting.");
}
}
Life Cycle of a Thread
During the life time of the thread, there are many states it can enter. They include the following:
Newborn state
Runnable State
Running State
Blocked state
Dead state
A thread can always in any one of the five states. It can move from one state to other via variety of
ways as shown in the fig.
Newborn state Stop

Start

Stop Dead State

Fig: Life Cycle


of Thread Running Runnable
State State
Yield
Stop

suspend() resume()
sleep() notify()
wait()

Blocked State

Dept.of ISE,RNSIT Page 23


Object Oriented Concepts with Java BCS306A
Newborn State: When we create a thread it is said to be in the new born state. At this state
we can do the following:
 schedule it for running using the start() method.
 Kill it using stop() method.

Runnable State: A runnable state means that a thread is ready for execution and waiting
for the availability of the processor. That is the thread has joined the queue of the threads for
execution. If all the threads have equal priority, then they are given time slots for execution
in the round rabin fashion, first-come, first-serve manner. The thread that relinquishes the
control will join the queue at the end and again waits for its turn. This is known as time
slicing.
Running State:

Running state: Running state means that the processor has given its time to the thread for it
execution. The thread runs until it relinquishes the control or it is preempted by the other
higher priority thread. As shown in the fig. a running thread can be preempted using the
suspen(), or wait(), or sleep() methods.

Blocked state: A thread is said to be in the blocked state when it is prevented from entering
into runnable state and subsequently the running state.

Dead state: Every thread has a life cycle. A running thread ends its life when it has
completed execution. It is a natural death. However we also can kill the thread by sending
the stop() message to it at any time.

The Thread Methods:

Sl No Method Name Description


1 run() Used to write the body of the thread
2 start() Used to start the thread
3 sleep() Used to make the thread sleep for milliseconds
4 suspend() Used to suspend a running thread
5 wait() Waits until further ordered
6 yield Used to give control to other thread before it turn comes
7 Stop() Used to stop the thread
8 resume() Used to start the blocked thread
9 notify() Used to notify the waiting thread
10 notifyAll() Used to notify theall waiting threads

Enumerations
 Enumerations included in JDK 5. An enumeration is a list of named constants.
It is similar to final variables.
 Enum in java is a data type that contains fixed set of constants.
 An enumeration defines a class type in Java. By making enumerations into
classes, so it can have constructors, methods, and instance variables.
 An enumeration is created using the enum keyword.
Ex:

Dept. of ISE,RNSIT Page 24


Object Oriented Concepts with Java BCS306A
enum Apple { Jonathan, GoldenDel, RedDel, Winesap, Cortland }

The identifiers Jonathan, GoldenDel, and so on, are called enumeration


constants.
Each is implicitly declared as a public, static final member of Apple.

Enumeration variable can be created like other primitive variable. It does notuse the
new for creating object.
Ex:Apple ap;

Ap is of type Apple, the only values that it can be assigned (or can contain)are
those defined by the enumeration. For example, this assigns:

ap = Apple.RedDel;

Example Code-1

enum Apple { Jonathan, GoldenDel, RedDel, Winesap, Cortland }

class EnumDemo
{
public static void main(String args[])
{
Apple ap;
ap = Apple.RedDel;
System.out.println("Value of ap: " + ap);// Value of ap: RedDel
ap = Apple.GoldenDel;
if(ap == Apple.GoldenDel)
System.out.println("ap contains GoldenDel.\n"); // ap contains GoldenDel.
switch(ap)
{
case Jonathan:
System.out.println("Jonathan is red.");
break;
case GoldenDel:
System.out.println("Golden Delicious is yellow.");// Golden Delicious is yellow

break;
case RedDel:
System.out.println("Red Delicious is red.");
break;
case Winesap:
System.out.println("Winesap is red.");
break;
case Cortland:
System.out.println("Cortland is red.");
break;
}
}
}

The values( ) and valueOf( ) Methods All enumerations automatically contain two predefined
methods: values( ) and valueOf( ).

Dept. of ISE,RNSIT Page 25


Object Oriented Concepts with Java BCS306A
Their general forms are shown here:

public static enum-type[ ] values( )

public static enum-type valueOf(String str)

The values( ) method returns an array that contains a list of the enumeration
constants.

The valueOf( ) method returns the enumeration constant whose value corresponds to thestring
passed in str.

Example Code-2:

enum Season { WINTER, SPRING, SUMMER, FALL } ;

class EnumExample1{

public static void main(String[] args) {

for (Season s : Season.values())

System.out.println(s);

Season s = Season.valueOf("WINTER");

System.out.println("S contains " + s);

} }

Example Code-3

class EnumExample5{

enum Day{ SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY,


SATURDAY}

public static void main(String args[]){

Day day=Day.MONDAY; switch(day){

case SUNDAY:

System.out.println("sunday");break;

case MONDAY:

System.out.println("monday");break;

default: System.out.println("other

Dept. of ISE,RNSIT Page 26


Object Oriented Concepts with Java BCS306A
day");

}}

Class Type Enumeration


enum Apple {

Jonathan(10), GoldenDel(9), RedDel(12), Winesap(15), Cortland(8);

private int price;

Apple(int p) { price = p; } int

getPrice() { return price; }

class EnumDemo3 {

public static void main(String args[])

{ Apple ap;

System.out.println("Winesap costs " + Apple.Winesap.getPrice() + " cents.\n");

System.out.println("All apple prices:");

for(Apple a : Apple.values())

System.out.println(a + " costs " + a.getPrice() + " cents.");

The Class type enumeration contains three things

The first is the instance variable price, which is used to hold the price of eachvariety
of apple.

The second is the Apple constructor, which is passed the price of an apple.The

third is the method getPrice( ), which returns the value of price.

Dept. of ISE,RNSIT Page 27


Object Oriented Concepts with Java BCS306A
When the variable ap is declared in main( ), the constructor for Apple is called once foreach
constant that is specified.

the arguments to the constructor are specified, by putting them inside parentheses after each
constant, as shown here:

Jonathan(10), GoldenDel(9), RedDel(12), Winesap(15), Cortland(8);

These values are passed to the parameter of Apple(),which then assigns this value to price.The
constructor is called once for each constant.

Because each enumeration constant has its own copy of price, you can obtain the price ofa
specified type of apple by calling getPrice().

For example, in main() the price of a Winesap is obtained by the following


call:Apple.Winesap.getPrice()

Enum Super class

All enumerations automatically inherit one: java.lang.Enum.

Enum class defines several methods that are available for use by all enumerations.

ordinal( )

To obtain a value that indicates an enumeration constant’s position in the list of constants. This
is called its ordinal value, and it is retrieved by calling the ordinal( ) method,shown here:

final int ordinal( )

It returns the ordinal value of the invoking constant. Ordinal values begin at zero. Thus, in the
Apple enumeration, Jonathan has an ordinal value of zero, GoldenDel has an ordinal value of 1,
RedDel has an ordinal value of 2, and so on.

compareTo( )

To compare the ordinal value of two constants of the same enumeration by using the
compareTo( ) method. It has this general form:

final int compareTo(enum-type e)

equals()

equals method is overridden method from Object class, it is used to compare the
enumeration constant. Which returns true if both constants are same.

Dept. of ISE,RNSIT Page 28


Object Oriented Concepts with Java BCS306A
Program to demonstrate the use of ordinal(), compareTo(), equals()

enum Apple { Jonathan, GoldenDel, RedDel, Winesap, Cortland }class

EnumDemo4

{ public static void main(String args[])

{ Apple ap, ap2, ap3;

System.out.println("Here are all apple constants" + " and their ordinal values: ");

for(Apple a : Apple.values())

System.out.println(a + " " + a.ordinal());

ap = Apple.RedDel; ap2

= Apple.GoldenDel;ap3 =

Apple.RedDel;

System.out.println();

if(ap.compareTo(ap2) < 0) System.out.println(ap + " comes before " + ap2);

if(ap.compareTo(ap2) > 0) System.out.println(ap2 + " comes before " + ap);

if(ap.compareTo(ap3) == 0) System.out.println(ap + " equals " + ap3);

System.out.println();

if(ap.equals(ap2)) System.out.println("Error!"); if(ap.equals(ap3))

System.out.println(ap + " equals " + ap3);if(ap == ap3)

System.out.println(ap + " == " + ap3);

Dept. of ISE,RNSIT Page 29


Object Oriented Concepts with Java BCS306A

Wrappers Classes
Java uses primitive types such as int or double, to hold the basic data types supportedby the
language.

The primitive types are not part of the object hierarchy, and they do not inherit Object.

Despite the performance benefit offered by the primitive types, there are times when youwill
need an object representation.

Many of the standard data structures implemented by Java operate on objects, whichmeans
that you can’t use these data structures to store primitive types.

To handle the above situation, Java provides type wrappers, which are classes that
encapsulate a primitive type within an object.

The type wrappers are Double, Float, Long, Integer, Short, Byte, Character, and Boolean. These
classes offer a wide array of methods that allow you to fully integrate the primitive types into
Java’s object hierarchy.

Character:

Character is a wrapper around a char. The constructor for Character is

Character(char ch)

Here, ch specifies the character that will be wrapped by the Character object being
created.

To obtain the char value contained in a Character object, call charValue( ), shownhere:

char charValue( )

Boolean:

Boolean is a wrapper around boolean values. It defines these constructors:

Boolean(boolean boolValue)

Boolean(String boolString)

In the first version, boolValue must be either true or false.

In the second version, if boolString contains the string “true” (in uppercase or
lowercase), then the new Boolean object will be true. Otherwise, it will be false.

To obtain a boolean value from a Boolean object, use booleanValue( ), shown here:

boolean booleanValue( )

It returns the boolean equivalent of the invoking object.

Dept. of ISE,RNSIT Page 30


Object Oriented Concepts with Java BCS306A

Integer Wrapper class example code:

Integer(int num)

Integer(String str)

class Wrap

{ public static void main(String args[])

Integer iOb = new Integer(100);

int i = iOb.intValue(); System.out.println(i +

" " + iOb);

This program wraps the integer value100 inside an Integer object called iOb.

The program then obtains this value by calling intValue() and stores the result in i.The

process of encapsulating a value within an object is called boxing.

Thus, in the program, this line boxes the value 100 into an Integer:

Integer iOb = new Integer(100);

The process of extracting a value from a type wrapper is called unboxing.The

program unboxes the value in iOb with this statement:

int i = iOb.intValue();

AutoBoxing

Auto boxing is the process by which a primitive type is automatically


encapsulated(boxed) into its equivalent type wrapper

whenever an object of that type is needed. There is no need to explicitly construct anobject.

Integer iOb = 100; // autobox an int

Auto-unboxing

Dept. of ISE,RNSIT Page 31


Object Oriented Concepts with Java BCS306A
Auto- unboxing is the process by which the value of a boxed object is automatically
extracted from a type wrapper when it is assigned to primitive type value is needed.

There is no need to call a method such as intValue( ).int i

= iOb; // auto-unbox

Example Program:

class AutoBoxUnBox

public static void main(String args[]) {

Integer iOb = 100; // autobox an intint

i = iOb; // auto-unbox

System.out.println(i + " " + iOb); // displays 100 100

Explain auto boxing and auto unboxing during method call

class AutoBox2 { static

int m(Integer v)

{ return v ; }

public static void main(String args[]) {

Integer iOb = m(100);

System.out.println(iOb);// 100

In the program, notice that m( ) specifies an Integer parameter and returns an intresult.

Inside main( ), m( ) is passed the value 100.

Because m( ) is expecting an Integer, this value is automatically boxed.

Then, m( ) returns the int equivalent of its argument. This causes v to be auto-unboxed.

Dept. of ISE,RNSIT Page 32


Object Oriented Concepts with Java BCS306A
Next, this int value is assigned to iOb in main( ), which causes the int return value to be
autoboxed.

Explain auto boxing and unboxing during expression evaluation

Autoboxing/Unboxing Occurs in Expressions autoboxing and unboxing take placewhenever a


conversion into an object or from an object is required.

This applies to expressions. Within an expression, a numeric object is automatically


unboxed.

The outcome of the expression is reboxed, if necessary. For example, consider thefollowing
program:

class AutoBox3

{ public static void main(String args[]) {

Integer iOb, iOb2; int i;

iOb = 100;

System.out.println("Original value of iOb: " + iOb);

++iOb; // auto unbox and rebox

System.out.println("After ++iOb: " + iOb);

iOb2 = iOb + (iOb / 3);

System.out.println("iOb2 after expression: " + iOb2);i =

iOb + (iOb / 3); // auto unbox and rebox

System.out.println("i after expression: " + i);

++iOb;

This causes the value in iOb to be incremented.

It works like this: iOb is unboxed, the value is incremented, and the result is reboxed.

Auto-unboxing also allows you to mix different types of numeric objects in an expression.
Once the values are unboxed,the standard type promotions and conversionsare applied.For
example, the following program is perfectly valid:

Integer iOb = 100; Double dOb = 98.6;

dOb = dOb + iOb; // type promoted to double

Dept. of ISE,RNSIT Page 33


ObjeObject Oriented Concepts with Java BCS306A

System.out.println("dOb after expression: " + dOb);Integer iOb = 2;

switch(iOb) {

case 1: System.out.println("one");break;

case 2: System.out.println("two");break;

default:

System.out.println("error");

When the switch expression is evaluated, iOb is unboxed and its int value is obtained.

As the examples in the program show, because of autoboxing/unboxing, using numericobjects in an


expression is both intuitive and easy.

Autoboxing/unboxing a Boolean and Character.

class AutoBox5 { public static void main(String args[]) {

Boolean b = true; // auto boxing booleanif(b)

System.out.println("b is true");// auto unboxed when used in conditional expressionCharacter ch = 'x'; //

box a char

char ch2 = ch; // unbox a char System.out.println("ch2 is "

+ ch2);

}}

The output is shown here:b is true ch2 is x

Dept. of ISE,RNSIT Page 34


ObjeObject Oriented Concepts with Java BCS306A

Enumerations
An enumeration is a list of named constants. In Java, enumerations define class types. That is, in Java, enumerations
can have constructors, methods and variables. An enumeration is created using the keyword enum. Following is an
example –

enum Person
{
Married, Unmarried, Divorced, Widowed
}

The identifiers like Married, Unmarried etc. are called as enumeration Constants. Each such constant is implicitly
considered as a public static final member of Person.

After defining enumeration, we can create a variable of that type. Though enumeration is a class type, we need not
use new keyword for variable creation, rather we can declare it just like any primitive data type. For example,
Person p= Person.Married;

We can use == operator for comparing two enumeration variables. They can be used in switch-case
also. Printing an enumeration variable will print the constant name. That is,
System.out.println(p); // prints as Married

Consider the following program to illustrate working of enumerations:

enum Person
{
Married, Unmarried, Divorced, Widowed
}

class EnumDemo
{
public static void main(String args[])
{
Person p1;
p1=Person.Unmarried; System.out.println("Value of p1 :" + p1);

Person p2= Person.Widowed;


if(p1==p2)
System.out.println("p1 and p2 are same");
else
System.out.println("p1 and p2 are different");

switch(p1)
{
case Married: System.out.println("p1 is Married");break;
case Unmarried: System.out.println("p1 is Unmarried");
break;
case Divorced: System.out.println("p1 is Divorced");break;
case Widowed: System.out.println("p1 is Widowed");
break;

Dept. of ISE,RNSIT Page 35


ObjeObject Oriented Concepts with Java BCS306A

}
}
}

The values() and valueOf() Methods


All enumerations contain two predefined methods: values() and valueOf(). Their general forms areshown here:
public static enum-type[] values()
public static enum-type valueOf(String str)

The values()method returns an array of enumeration constants. The valueOf()method returns theenumeration
constant whose value corresponds to the string passed in str.

enum Person
{
Married, Unmarried, Divorced, Widowed
}
class EnumDemo
{ public static void main(String args[])
{ Person p;

System.out.println("Following are Person constants:");Person


all[]=Person.values();

for(Person p1:all)
System.out.println(p1);

p=Person.valueOf("Married"); System.out.println("p contains "+p);


}
}
Output:
Following are Person constants:
Married
Unmarried
Divorced
Widowed
p contains Married

Java Enumerations are Class Types


Java enumeration is a class type. That is, we can write constructors, add instance variables and methods, and even
implement interfaces. It is important to understand that each enumeration constant is an object of its
enumeration type. Thus, when you define a constructor for an enum, the constructor is called when each
enumeration constant is created. Also, each enumeration constant has its own copy of any instance variables
defined by the enumeration.

enum Apple
{
Jonathan(10), GoldenDel(9), RedDel(12), Winesap(15), Cortland(8);private int price;

Apple(int p)
{

Dept. of ISE,RNSIT Page 36


ObjeObject Oriented Concepts with Java BCS306A

price = p;
}

int getPrice()
{
return price;
}
}

class EnumDemo
{
public static void main(String args[])
{
Apple ap;
System.out.println("Winesap costs " + Apple.Winesap.getPrice());System.out.println("All apple

prices:");

for(Apple a : Apple.values())
System.out.println(a + " costs " + a.getPrice() + " cents.");
}
}

Output:
Winesap costs 15
All apple prices:
Jonathan costs 10 cents.
GoldenDel costs 9 cents.
RedDel costs 12 cents.
Winesap costs 15 cents.
Cortland costs 8 cents.

Here, we have member variable price, a constructor and a member method. When the variable ap isdeclared in
main( ), the constructor for Apple is called once for each constant that is specified.

Although the preceding example contains only one constructor, an enum can offer two or moreoverloaded forms,
just as can any other class. Two restrictions that apply to enumerations:
– an enumeration can’t inherit another class.
– an enum cannot be a superclass.

Enumerations Inherits Enum


All enumerations automatically inherited from java.lang.Enum. This class defines several methods that are
available for use by all enumerations. We can obtain a value that indicates an enumeration constant’s position in the
list of constants. This is called its ordinal value, and it is retrieved by calling the ordinal() method, shown here:
final int ordinal( )

It returns the ordinal value of the invoking constant. Ordinal values begin at zero. We can compare the ordinal
value of two constants of the same enumeration by using the compareTo() method. It has this general form:
final int compareTo(enum-type e)

Dept. of ISE,RNSIT Page 37


ObjeObject Oriented Concepts with Java BCS306A

The usage will be –


e1.compareTo(e2);

Here, e1 and e2 should be the enumeration constants belonging to same enum type. If the ordinal value of e1 is less
than that of e2, then compareTo() will return a negative value. If two ordinal values are equal, the method will
return zero. Otherwise, it will return a positive number.

We can compare for equality an enumeration constant with any other object by using equals( ), which overrides the
equals( ) method defined by Object.

enum Person
{
Married, Unmarried, Divorced, Widowed
}

enum MStatus
{
Married, Divorced
}

class EnumDemo
{
public static void main(String args[])
{
Person p1, p2, p3;

MStatus m=MStatus.Married; System.out.println("Ordinal values

are: ");

for(Person p:Person.values())
System.out.println(p + " has a value " + p.ordinal());

p1=Person.Married; p2=Person.Divorced;
p3=Person.Married;

if(p1.compareTo(p2)<0)
System.out.println(p1 + " comes before "+p2);else
if(p1.compareTo(p2)==0)
System.out.println(p1 + " is same as "+p2);
else
System.out.println(p1 + " comes after "+p2);

if(p1.equals(p3))
System.out.println("p1 & p3 are same");

if(p1==p3)
System.out.println("p1 & p3 are same");

if(p1.equals(m))
System.out.println("p1 & m are same");

Dept. of ISE,RNSIT Page 38


ObjeObject Oriented Concepts with Java BCS306A

else
System.out.println("p1 & m are not same");

//if(p1==m) Generates error


//System.out.println("p1 & m are same");
}
}

Type Wrappers
Java uses primitive types (also called simple types), such as int or double, to hold the basic data types supported by
the language. Primitive types, rather than objects, are used for these quantities for the sake of performance. Using
objects for these values would add an unacceptable overhead to even the simplest of calculations. Thus, the
primitive types are not part of the object hierarchy, and they do not inherit Object. Despite the performance benefit
offered by the primitive types, there are times when you will need an object representation. For example, you can’t
pass a primitive type by reference to a method. Also, many of the standard data structures implemented by Java
operate on an object, which means that you can’t use these data structures to store primitive types. To handle these
(and other) situations, Java provides type wrappers, which are classes that encapsulate a primitive type within an
object.

The type wrappers are Double, Float, Long, Integer, Short, Byte, Character, and Boolean. These classes offer a
wide array of methods that allow you to fully integrate the primitive types into Java’s objecthierarchy.

Primitive Wrapper
boolean java.lang.Boolean
byte java.lang.Byte
char java.lang.Character
double java.lang.Double
float java.lang.Float
int java.lang.Integer
long java.lang.Long
short java.lang.Short
void java.lang.Void

 Character Wrappers: Character is a wrapper around a char. The constructor for Character is
Character(char ch)

Here, ch specifies the character that will be wrapped by the Character object being created. Toobtain the
char value contained in a Character object, call charValue(), shown here:
char charValue( )

It returns the encapsulated character.

 Boolean Wrappers: Boolean is a wrapper around boolean values. It defines these constructors:

Dept. of ISE,RNSIT Page 39


ObjeObject Oriented Concepts with Java BCS306A

Boolean(boolean boolValue)
Boolean(String boolString)

In the first version, boolValue must be either true or false. In the second version, if boolString
contains the string “true” (in uppercase or lowercase), then the new Boolean object will be true.
Otherwise, it will be false. To obtain a boolean value from a Boolean object, useboolean
booleanValue( )

It return the boolean equivalent of the invoking object.

 The Numeric Type Wrappers: The most commonly used type wrappers are those that represent numeric
values. All of the numeric type wrappers inherit the abstract class Number. Number declares methods that
return the value of an object in each of the different number formats. Thesemethods are shown here:
byte byteValue( ) double
doubleValue( )float floatValue(
) int intValue( )
long longValue( ) short
shortValue( )
For example, doubleValue( ) returns the value of an object as a double, floatValue( ) returns thevalue as a
float, and so on. These methods are implemented by each of the numeric type wrappers.

All of the numeric type wrappers define constructors that allow an object to be constructed from a given
value, or a string representation of that value. For example, here are the constructors defined for Integer:
Integer(int num)
Integer(String str)

If str does not contain a valid numeric value, then a NumberFormatException is thrown. All of the type
wrappers override toString(). It returns the human-readable form of the value contained within the wrapper.
This allows you to output the value by passing a type wrapper object to println(), for example, without
having to convert it into its primitive type.

Dept. of ISE,RNSIT Page 40


ObjeObject Oriented Concepts with Java BCS306A

EXAMPLE

public static void main(String args[])


{
Character ch=new Character('#'); System.out.println("Character is " +
ch.charValue());

Boolean b=new Boolean(true); System.out.println("Boolean is " +


b.booleanValue());

Boolean b1=new Boolean("false"); System.out.println("Boolean is " +


b1.booleanValue());

Integer iOb=new Integer(12); //boxing


int i=iOb.intValue(); //unboxing
System.out.println(i + " is same as " + iOb);

Integer a=new Integer("21"); int


x=a.intValue(); System.out.println("x is " + x);

String s=Integer.toString(25); System.out.println("s is " +s);


}
}

Output:
Character is #
Boolean is true
Boolean is false
12 is same as 12
x is 21
s is 25

Dept. of ISE,RNSIT Page 41

You might also like