0% found this document useful (0 votes)
3 views47 pages

Unit-2 Multithreading in Java

The document provides an overview of threads and processes in Java, explaining that a thread is a single path of execution within a program, while a process is a program in execution that can contain multiple threads. It highlights the advantages of multithreading, including improved performance and resource utilization, and details the methods and classes used to create and manage threads in Java. Additionally, it outlines how to create threads by extending the Thread class or implementing the Runnable interface.
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)
3 views47 pages

Unit-2 Multithreading in Java

The document provides an overview of threads and processes in Java, explaining that a thread is a single path of execution within a program, while a process is a program in execution that can contain multiple threads. It highlights the advantages of multithreading, including improved performance and resource utilization, and details the methods and classes used to create and manage threads in Java. Additionally, it outlines how to create threads by extending the Thread class or implementing the Runnable interface.
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/ 47

IMS Engineering College

NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.


Tel: (0120) 4940000
Department: Computer Science and Engineering

What is Thread in Java


A thread in Java simply represents a single independent path of execution of a group of
statements. It is the flow of execution, from beginning to end, of a task.
Normal java programs have single flow of controls, this program begins, runs through sequence
of executions and finally ends. At any given point of time, there is only one statement under
execution.
When a program contains a single flow of control, it is called single-threaded program. In a
single thread program, there is a beginning, a body, and an end. Single-threaded programs
execute commands sequentially, one after the other, in just one flow of control.
This means the program can only perform one task at a time before moving on to the next.
Each command must wait for the previous one to complete before it can start.

We can also create more than one execution thread in a program that can be used to perform
multiple tasks simultaneously. When we create more than one thread in a program, each thread
has its own path of execution and all the threads share the same memory address space, data,
and code in a program.
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science and Engineering

What is Process in Java?

Thread in Java is the smallest unit of executable code in a program. It helps to divide a program
into multiple parts to speed up the process.
A process is a program that executes as a single thread. In other words, when an executable
program is loaded into memory, it is called process.
Points to be Noted:
1. Every individual process has its own separate memory address space and can execute a
different program.
2. Each process can have more than one thread.
3. Each process communicates through the operating system, files, and network.
When we will create a new thread in a program, it shares the same memory address space
with other threads in a program, whereas every individual process has its own separate
memory address space.
Therefore, creating a thread takes fewer resources than creating a new process.

Multiple Threads are independent of each other. At a time, only one thread is executed.
If an exception occurs in one thread, it doesn’t affect other threads.
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science and Engineering

Why Java threads are lightweight process?

Java Threads are also known as lightweight threads or light-weight processes. It means that
they can be executed in the same memory space because all the threads in the main application
program share the same address space in the memory so that they can easily communicate
among themselves. Thus, they also take less space in memory and less processor time.

Main Thread in Java

When a Java program starts up, one thread begins running immediately. This is usually called
the main thread of our program, because it is the one that is executed when our 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, we 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:.
Thread obj = Thread.currentThread();
This method returns a reference to the thread in which it is called. Once we have a
reference to the main thread, you can control it just like any other thread.
Program code:
public class MainThread1 {
public static void main(String[] args)
{
Thread obj = Thread.currentThread();
System.out.println("Current thread is " +obj); // line 8
System.out.println("Name of current thread is " +obj.getName());
}
}
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science and Engineering

Multithreading

Multi-threading programming approach is one of the most powerful features of Java. It


not only makes our program more responsive and interactive but also improves
performance. Java uses a multithreading concept to handle several tasks simultaneously,
making programs faster and more efficient.
Multi-threading means multiple flow of control. Multi-threading programming is a conceptual
paradigm for programming where one can divide a program into two or more processes which
can be run in parallel. There are two main advantages of multi-threading :
Fist, program with multiple threads will, in general, result in better utilization of system
resources, including the CPU, because another line of execution can grab the CPU when one
line of execution is blocked.
Second, there are several problems better solved by multiple threads. For example, we can
easily write a multi-threaded program to show animation, play music, display documents, and
down load files from the network at the same time.
Java is a multi-threaded language. Java allows to write a program where more than one
processes can be executed concurrently within the single program.
Java's threads are often referred to as light weight threads, which means that they run in the
same memory space. Because Java threads run in the same memory space, they can easily
communicate among themselves because an object in one thread can call a method in another
thread without any overhead from the operating system.
When a program contains multiple flows of control, it is called multithreaded program.
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science and Engineering

Java program has three threads, one main and two others. The other two threads,
ThreadA and ThreadB are created and started from the main thread.
Once initiated by the main thread, thread ThreadA and ThreadB run simultaneously and share
the resources together.
When a program contains more than one thread, the CPU can switch between two threads to
execute them at the same time. The switching between two threads is known as context switch.
This technique is useful for those applications which need multiple tasks to be done
simultaneously. In a single processor system, multiple threads share CPU time that is known
as time-sharing.
Basics of a thread
As with the Java concepts, everything about thread are defined in a class Thread. The Thread
class encapsulates all of the control one will need over threads.
In Java, Thread class contains several constructors for creating threads for tasks and methods
for controlling threads. It is a predefined class declared in java.lang default package.
Each thread in Java is created and controlled by a unique object of the Thread class. An object
of thread controls a thread running under JVM.
Thread class contains various methods that can be used to start, control, interrupt the execution
of a thread, and for many other thread related activities in a program.
Thread class extends Object class and it implements Runnable interface. The declaration of
thread class is as follows:
public class Thread
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science and Engineering

extends Object
implements Runnable

Thread Class Constructor

The various constructors of thread class are defined in java.lang package that can be used to
create an object of thread are as follows:
1. Thread(): This is a basic and default constructor without parameters. It simply creates an
object of Thread class.
2. Thread(String name): It creates a new thread object with specified name to a thread.
3. Thread(Runnable r): It creates a thread object by passing a parameter r as a reference to
an object of the class that implements Runnable interface.
4.
Thread(Runnable r, String name): This constructor creates a thread object by passing
two arguments r and name. Here, variable r is a reference of an object of class that
implements Runnable interface.

Methods of Thread Class in Java

Thread class provides various static methods that are as follows:


IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science and Engineering

1. currentThread(): The currentThread() returns the reference of currently executing thread.


Since this is a static method, so we can call it directly using the class name. The general
syntax for currentThread() is as follows:
Syntax:
public static Thread currentThread()
2. sleep(): The sleep() method puts currently executing thread to sleep for specified number
of milliseconds. This method is used to pause the current thread for specified amount of time
in milliseconds.
Since this method is static, so we can access it through Thread class name. The general
syntax of this method is as follows:
Syntax:
public static void sleep(long milliseconds) throws InterruptedException
The general syntax for overloaded version of sleep method is as follows:
Syntax:
public static void sleep(long milliseconds, int nanoseconds ) throw InterruptedException
The overloaded version of sleep() method is used to pause specified period of time in
milliseconds and nanoseconds. Both methods throw InterruptedException and must be used
within Java try-catch block.

3. yield(): The yield() method pauses the execution of current thread and allows another
thread of equal or higher priority that are waiting to execute. Currently executing thread give
up the control of the CPU. The general form of yield() method is as follows:
Syntax:
public static void yield()
4. activeCount(): This method returns the number of active threads.
Syntax:
public static int activeCount()
Since this method is static, so it can be accessed through Thread class name. It does not
accept anything.
The instance methods of Thread class are as follows:
1. start(): The start() method is used to start the execution of a thread by calling its run()
method. JVM calls the run() method on the thread. The general syntax for start() method is as
follows:
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science and Engineering

Syntax:
public void start()
2. run(): The run() method moves the thread into running state. It is executed only after the
start() method has been executed. The general syntax is as follows:
Syntax:
public void run()
3. getName(): This method returns the name of the thread. The return type of this method is
String. The general form of this method is:
Syntax:
public final String getName()
4. setName(): This method is used to set the name of a thread. It takes an argument of type
String. It returns nothing.
Syntax:
public final void setName(String name)
5. getPriority(): This method returns the priority of a thread. It returns priority in the form of
an integer value ranging from 1 to 10. The maximum priority is 10, the minimum priority is 1,
and normal priority is 5.
Syntax:
public final int getPriority() // Return type is an integer.
6. setPriority(): This method is used to set the priority of a thread. It accepts an integer value
as an argument. The general syntax is given below:
Syntax:
public final void setPriority(int newPriority)
7. isAlive(): This method is used to check the thread is alive or not. It returns a boolean value
(true or false) that indicates thread is running or not. The isAlive() method is final and native.
The general syntax for isAlive() method is as follows:
Syntax:
public final native boolean isAlive()
8. join(): The join() method is used to make a thread wait for another thread to terminate its
process. The general syntax is
Syntax:
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science and Engineering

public final void join() throw InterruptedException


This method throws InterruptedException and must be used within a try-catch block.
9. stop(): This method is used to stop the thread. This method is deprecated because it is
inherently unsafe to useThe general form for this method is as follows:
Syntax:
public final void stop()
This method neither accepts anything nor returns anything.
10. suspend(): The suspend() method is used to suspend or pause a thread. This is deprecated
because it is deadlock prone.
Syntax:
public final void suspend()
11. resume(): This method is used to resume the suspended thread. Since suspend() method
is deprecated, resume() method is also deprecated. It neither accepts anything nor returns
anything.
Syntax:
public final void resume()
12. isDaemon(): This method is used to check the thread is daemon thread or not.
Syntax:
public final boolean isDaemon()

Creating and Running a Thread

There are two ways to define a thread:


• One is by extending java.lang.Thread class
• Another is by implementing java.lang.Runnable interface

Using the sub classing thread ( Extending Thread Class in Java)

Extending Thread class is the easiest way to create a new thread in Java.
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science and Engineering

In this way to create a thread is to create a new class that extends Thread, and then to create an
instance of that class.
The extending class must override the run( ) method, which is the entry point for the new
thread.
It must also call start( ) to begin execution of the new thread.
The following steps can be followed to create our own thread in Java.

1. Create a class that extends the Thread class. In order to extend a thread, we will use a
keyword extends. The Thread class is found in java.lang package.
.
The syntax for creating a new class that extends Thread class is as follows:
Class Myclass extends Thread
2. Now in this newly created class, define a method run(). Here, run() method acts as entry
point of the new thread. The run() method contains the actual task that thread will perform.
Thus, we override run() method of Thread class.
public void run()
{
// statements to be executed.
}
3. Create an object of newly created class so that run() method is available for execution. The
syntax to create an object of Myclass is as follows:
Myclass obj = new Myclass();

4. Now create an object of Thread class and pass the object reference variable created to the
constructor of Thread class.
Thread t = new Thread(obj);
or,
Thread t = new Thread(obj, "threadname");
5. Run the thread. For this, we need to call to start() method of Thread class because we cannot
call run() method directly. The syntax to call start() method is as follows:
t.start();
Now, the thread will start execution on the object of Myclass, and statements inside run()
method will be executed while calling it. By following all the above steps, we can create a
Thread in Java.
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science and Engineering

Creating and running threads using sub classing Thread

Custom thread class.


public class MyThread extends Thread
{
// Override the run method in Runnable.
public void run()
{
System.out.println("New thread running ");
}
public static void main(String[] args)
{
System.out.println("Main thread running");

// Create an object of MyThread class.


MyThread th = new MyThread();

// Create an object of Thread class and pass the object reference variable th.
Thread t = new Thread(th);

// Now run thread on the object. For this, call start() method using reference variable t.
t.start(); // This thread will execute statements inside run() method of MyThread object.
}
}
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science and Engineering

/* Creating three threads using the class Thread and then running them concurrently. */
class ThreadA extends Thread
{
public void run( )
{
for(int i = 1; i <= 5; i++)
{
System.out.println("From Thread A with i = "+ -1*i);
}
System.out.println("Exiting from Thread A ...");
}
}
class ThreadB extends Thread {
public void run( ) {
for(int j = 1; j <= 5; j++) {
System.out.println("From Thread B with j= "+2* j);
}
System.out.println("Exiting from Thread B ...");
}
}
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science and Engineering

class ThreadC extends Thread{


public void run( ) {
for(int k = 1; k <= 5; k++) {
System.out.println("From Thread C with k = "+ (2*k-1));
}
System.out.println("Exiting from Thread C ...");
}
}

public class Mythread8 {


public static void main(String args[]) {
ThreadA a = new ThreadA();
ThreadB b = new ThreadB();
ThreadC c = new ThreadC();
a.start();
b.start();
c.start();
System.out.println("... Multithreading is over ");
}
}
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science and Engineering

In the above simple example, three threads (all of them are of some type) will be executed
concurrently. Note that a thread can be directed to start its body by start() method.

Creating Thread Using the Runnable interface

Using the Runnable interface : A second way to create threads is to make use of the Runnable
interface. With this approach, first we have to implement the Runnable interface. [Runnable
interface is already defined in the system package java.lang with a single method run().
To implement Runnable, a class need only implement a single method called run( ), which
is declared like this: public void run().
Inside run( ), we will define the code that constitutes the new thread. It is important to
understand that run( ) can call other methods, use other classes, and declare variables, just like
the main thread can.
The only difference is that run( ) establishes the entry point for another, concurrent thread of
execution within our program. This thread will end when run( ) returns.
After we create a class that implements Runnable, we will instantiate an object of type Thread
from within that class.
Thread defines several constructors. The one that we will use is shown here:
Thread(Runnable threadOb, String threadName)
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science and Engineering

In this constructor, threadOb is an instance of a class that implements the Runnable interface.
This defines where execution of the thread will begin.
The name of the new thread is specified by threadName.
After the new thread is created, it will not start running until we call its start( ) method, which
is declared within
Thread. In essence, start( ) executes a call to run( ).
The start( ) method is shown here: void start( )

/* Creating three threads using the Runnable interface and then running them
concurrently. */
class ThreadX implements Runnable
{
public void run( ) {
for(int i = 1; i <= 5; i++) {
System.out.println("Thread X with i = "+ -1*i);
}
System.out.println("Exiting Thread X ...");
}
}

class ThreadY implements Runnable {


public void run( ) {
for(int j = 1; j <= 5; j++) {
System.out.println("Thread Y with j = "+ 2*j);
}
System.out.println("Exiting Thread Y ...");
}
}
class ThreadZ implements Runnable{
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science and Engineering

public void run( ) {


for(int k = 1; k <= 5; k++) {
System.out.println("Thread Z with k = "+ (2*k-1));
}
System.out.println("Exiting Thread Z ...");
}
}

public class Mythread9 {


public static void main(String args[]) {
ThreadX x = new ThreadX();
Thread t1 = new Thread(x);

ThreadY y = new ThreadY();


Thread t2 = new Thread(y);

//ThreadZ z = new ThreadZ();


//Thread t3 = new Thread(z);
Thread t3 = new Thread(new ThreadZ());

t1.start();
t2.start();
t3.start();

System.out.println("... Multithreading is over ");


}
}
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science and Engineering

Note : Note in the above example, how after implementing objects, their thread is created and
their threads start execution. Also note that, a class instance with the run( ) method defined
within must be passed in as an argument in creating the thread instance so that when the start()
method of this Thread instance is called, Java run time knows which run() method to execute.
This alternative method of creating a thread is useful when the class defining run() method
needs to be a sub class of other classes; the class can inherit all the data and methods of the
super class.

Life cycle of threads

Each thread is always in one of five states:


1. Newborn State
2. Runnable State
3. Running State
4. Blocked State
5. Dead State
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science and Engineering

Newborn : When a thread is created (by new statement ) but not yet to run, it is called in
Newborn state. In this state, the local data members are allocated and initialized.

Runnable : The Runnable state means that a thread is ready to run and is awaiting for the
control of the processor, or in other words, threads are in this state in a queue and wait their
turns to be executed.

Running : Running means that the thread has control of the processor, its code is currently
being executed and thread will continue in this state until it get preempted by a higher priority
thread, or until it relinquishes control.

Blocked : A thread is Blocked means that it is being prevented from the Runnable ( or Running)
state and is waiting for some event in order for it to re enter the scheduling queue.

Dead : A thread is Dead when it finishes its execution or is stopped (killed) by another thread.
Threads move from one state to another via a variety of means. The common methods for
controlling a thread's state is shown in above figure.

Using Thread methods :

start ( ) : A newborn thread with this method enter into Runnable state and Java run time create
a system thread context and starts it running. This method for a thread object can be called once
only.
stop( ) : This method causes a thread to stop immediately. This is often an abrupt way to end a
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science and Engineering

thread.
suspend( ) : This method is different from stop( ) method. It takes the thread and causes it to
stop running and later on can be restored by calling it again.

resume ( ) : This method is used to revive a suspended thread. There is no gurantee that the
thread will start running right way, since there might be a higher priority thread running already,
but, resume()causes the thread to become eligible for running.

sleep (int n ) : This method causes the run time to put the current thread to sleep for n
milliseconds. After n milliseconds have expired, this thread will become elligible to run again.

yield( ) : The yield() method causes the run time to switch the context from the current thread
to the next available runnable thread. This is one way to ensure that the threads at lower priority
do not get started.
Other methods like wait(), notify(), join() etc.

Suspending, Resuming, and Stopping Threads

Prior to Java 2, a program used suspend( ), resume( ), and stop( ), which are methods defined
by Thread, to pause, restart, and stop the execution of a thread.
But these methods were deprecated by Java 2 because they could result in system failures.
Here’s why. The suspend( ) method of the Thread class was deprecated by Java 2 several years
ago. This was done because suspend() can sometimes cause serious system failures. Assume
that a thread has obtained locks on critical data structures. If that thread is suspended at that
point, those locks are not relinquished. Other threads that may be waiting for those resources
can be deadlocked.
The resume( ) method is also deprecated. It does not cause problems, but cannot be used
without the suspend( ) method as its counterpart.
The stop( ) method of the Thread class, too, was deprecated by Java 2. This was done because
this method can sometimes cause serious system failures.
We can’t now use the suspend( ), resume( ), or stop( ) methods to control a thread.
Instead, a thread must be designed so that the run( ) method periodically checks to determine
whether that thread should suspend, resume, or stop its own execution.
Typically, this is accomplished by establishing a flag variable that indicates the execution state
of the thread.
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science and Engineering

As long as this flag is set to “running,” the run( ) method must continue to let the thread execute.
If this variable is set to “suspend,” the thread must pause.
If it is set to “stop,” the thread must terminate. Of course, a variety of ways exist in which to
write such code, but the central theme will be the same for all programs.

/* Use of yield(), stop() and sleep() methods old way*/


class ClassA extends Thread
{
public void run()
{
System.out.println("Start Thread A ....");
for(int i = 1; i <= 5; i++)
{
if (i==1)
Thread.yield();
System.out.println("From Thread A: i = "+ i);
}
System.out.println("... Exit Thread A");
}
}

class ClassB extends Thread


{
public void run()
{
System.out.println("Start Thread B ....");
for(int j = 1; j <= 5; j++)
{
System.out.println("From Thread B: j = "+ j);
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science and Engineering

if (j==2)
stop();
}
System.out.println("... Exit Thread B");
}
}

class ClassC extends Thread


{
public void run()
{
System.out.println("Start Thread C ....");
for(int k = 1; k <= 5; k++)
{
System.out.println("From Thread B: j = "+ k);
if (k==3)
{
try
{
sleep(1000);
}
catch(Exception e)
{

}
}
}
System.out.println("... Exit Thread C");
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science and Engineering

}
}

public class Mythread2


{
public static void main (String args[])
{
ClassA t1 = new ClassA();
ClassB t2 = new ClassB();
ClassC t3 = new ClassC();
t1.start();
t2.start();
t3.start();
System.out.println("... End of executuion ");
}
}
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science and Engineering

/* Use of suspend() and resume() methods old way*/

class Thread1 extends Thread {


public void run( ) {
try{
System.out.println (" First thread starts running" );
sleep(10000);
System.out.println (" First thread finishes running" );
}
catch(Exception e){ }
}
}

class Thread2 extends Thread {


public void run( ) {
try{
System.out.println ( "Second thread starts running");
System.out.println ( "Second thread is suspended itself ");
suspend( );
System.out.println (" Second thread runs again" );
}
catch(Exception e){ }
}
}

class Mythread11{
public static void main (String args[ ] ){
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science and Engineering

try{
Thread1 first = new Thread1( ); // It is a newborn thread i.e. in Newborn
state
Thread2 second= new Thread2( ); // another new born thread

first.start( ); // first is scheduled for running


second.start( ); // second is scheduled for running

System.out.println("Revive the second thread" ); // If it is suspended


second.resume( );

System.out.println ("Second thread went for 10 seconds sleep " );


second.sleep (10000);

System.out.println ("Wake up second thread and finishes running" );


System.out.println ( " Demonstration is finished ");
}
catch(Exception e){ }
}
}
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science and Engineering

// Suspending and resuming a thread the modern way.


The following example illustrates how the wait( ) and notify( ) methods that are inherited from
Object can be used to control the execution of a thread.
The NewThread class contains a boolean instance variable named suspendFlag, which is used
to control the execution of the thread.
It is initialized to false by the constructor.
The run( ) method contains a synchronized statement block that checks suspendFlag.
If that variable is true, the wait( ) method is invoked to suspend the execution of the thread.
The mysuspend( ) method sets suspendFlag to true. The myresume( ) method sets suspendFlag
to false and invokes notify( ) to wake up the thread.
Finally, the main( ) method has been modified to invoke the mysuspend( ) and myresume( )
methods.
class NewThread implements Runnable
{
String name; // name of thread
Thread t;
boolean suspendFlag;
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science and Engineering

NewThread(String threadname) {
name = threadname;
t = new Thread(this, name);
System.out.println("New thread: " + t);
suspendFlag = false;
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);
synchronized(this) {
while(suspendFlag) {
wait();
}
}
}
} catch (InterruptedException e) {
System.out.println(name + " interrupted.");
}
System.out.println(name + " exiting.");
}
synchronized void mysuspend() {
suspendFlag = true;
}
synchronized void myresume() {
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science and Engineering

suspendFlag = false;
notify();
}
}
class SuspendResume
{
public static void main(String args[])
{
NewThread ob1 = new NewThread("One");
NewThread ob2 = new NewThread("Two");
try {
Thread.sleep(1000);
ob1.mysuspend();
System.out.println("Suspending thread One");
Thread.sleep(1000);
ob1.myresume();
System.out.println("Resuming thread One");
ob2.mysuspend();
System.out.println("Suspending thread Two");
Thread.sleep(1000);
ob2.myresume();
System.out.println("Resuming thread Two");
} catch (InterruptedException e) {
System.out.println("Main thread Interrupted");
}
// wait for threads to finish
try {
System.out.println("Waiting for threads to finish.");
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science and Engineering

ob1.t.join();
ob2.t.join();
} catch (InterruptedException e) {
System.out.println("Main thread Interrupted");
}
System.out.println("Main thread exiting.");
}
}

Thread priority
Thread priority in Java is a number assigned to a thread that is used by Thread scheduler to
decide which thread should be allowed to execute.
In Java, each thread is assigned a different priority that will decide the order (preference) in
which it is scheduled for running.
Thread priorities are represented by a number from 1 to 10 that specifies the relative priority
of one thread to another. The thread with the highest priority is selected by the scheduler to be
executed first.
Thread priorities are integers that specify the relative priority of one thread to another. As an
absolute value, a priority is meaningless; a higher-priority thread doesn’t run any faster than a
lower-priority thread if it is the only thread running.
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science and Engineering

Instead, a thread’s priority is used to decide when to switch from one running thread to the
next.
This is called a context switch. The rules that determine when a context switch takes place are
simple:
• 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 are examined, 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-priority thread
that does not yield the processor is simply preempted—no matter what it is doing— by a higher-
priority thread. Basically, as soon as a higher-priority thread wants to run, it does. This is called
preemptive multitasking.
In cases where two threads with the same priority are competing for CPU cycles, the situation
is a bit complicated. For operating systems such as Windows, threads of equal priority are time-
sliced automatically in round-robin fashion. For other types of operating systems, threads of
equal priority must voluntarily yield control to their peers. If they don’t, the other threads will
not run.
To set a thread’s priority, we can use the setPriority( ) method, which is a member of
Thread.
This is its general form:
final void setPriority(int level)
or
ThreadName. 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.
MIN_PRIORITY = 1
NORM_PRIORITY = 5
MAX_PRIORITY = 10

/* Setting priority to threads */


IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science and Engineering

class ThreadA extends Thread{


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

class ThreadB extends Thread{


public void run() {
System.out.println("Start Thread B ....");
for(int j = 1; j <= 5; j++) {
System.out.println("From Thread B: j = "+ j);
}
System.out.println("... Exit Thread B");
}
}

class ThreadC extends Thread{


public void run() {
System.out.println("Start Thread C ....");
for(int k = 1; k <= 5; k++) {
System.out.println("From Thread C: k = "+ k);
}
System.out.println("... Exit Thread C");
}
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science and Engineering

class Mythread12
{
public static void main (String args[])
{
ThreadA t1 = new ThreadA();
ThreadB t2 = new ThreadB();
ThreadC t3 = new ThreadC();

t2.setPriority(Thread.MAX_PRIORITY);
t1.setPriority(t1.getPriority() + 1);
t3.setPriority(Thread.MIN_PRIORITY);

t1.start();
t2.start();
t3.start();
System.out.println("... End of executuion ");
}
}
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science and Engineering

We can obtain the current priority setting by calling the getPriority( ) method of Thread,
shown here:
final int getPriority( )
Implementations of Java may have radically different behavior when it comes to scheduling.
Most of the inconsistencies arise when you have threads that are relying on pre-emptive
behaviour, instead of cooperatively giving up CPU time. The safest way to obtain predictable,
cross-platform behavior with Java is to use threads that voluntarily give up control of the CPU.
public class Mythread13 implements Runnable {
public void run()
{
System.out.println(Thread.currentThread()); // This method is static.
}
public static void main(String[] args)
{
Mythread13 a = new Mythread13();
Thread t = new Thread(a, "NewThread");

System.out.println("Priority of Thread: " +t.getPriority());


IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science and Engineering

System.out.println("Name of Thread: " +t.getName());


t.start();
}
}

Synchronization and Inter-Thread Communication


Problems may occur when two or more threads are accessing the same data concurrently, for
example, one thread stores data into the shared object and the other threads reads data, there
can be synchronization problem if the first thread has not finished storing the data before the
second one goes to read it.
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.

Synchronization
To solve the critical section problem, one usual concept is known what is called monitor. A
monitor is an object which is used as a mutually exclusive lock ( called mutex).
Only one thread may own a monitor at a given time.
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science and Engineering

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.
In fact, all Java object have their own implicit monitor associated with them. To enter an
object’s monitor, just call a method that has been modified with the synchronized keyword.
Here, the key word synchronized is used by which method (s) or block of statements can be
made protected from the simultaneous access.
While a thread is inside a synchronized method, all other threads that try to call it (or any other
synchronized method) on the same instance have to wait. To exit the monitor and relinquish
control of the object to the next waiting thread, the owner of the monitor simply returns from
the synchronized method.

Program code 1:
class Table {
void printTable(int x)
{
synchronized(this) // Synchronized block.
{
for(int i = 1; i <= 3; i++)
{
System.out.println(x * i);
try
{
Thread.sleep(400);
}
catch(InterruptedException ie)
{
System.out.println(ie);
}
}
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science and Engineering

}
}
}
class Thread1 extends Thread
{
Table t;
Thread1(Table t)
{
this.t = t;
}
public void run()
{
t.printTable(2);
}
}
class Thread2 extends Thread
{
Table t;
Thread2(Table t)
{
this.t = t;
}
public void run()
{
t.printTable(10);
}
}
public class Mythread6 {
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science and Engineering

public static void main(String[] args)


{
Table t = new Table();
Thread1 t1 = new Thread1(t);
Thread2 t2 = new Thread2(t);
t1.start();
t2.start();
}
}

Let us illustrate this mechanism with a simple example.


Suppose, we want to maintain a bank account of customers. Several transactions, such as
deposite some amount to an account and withdraw some amount from an account etc. are
possible. Now, for a given account, if two or more transactions come simultaneously then only
one transaction should be allowed at a time instead of simulataneous transaction processing so
that data inconsistency will never occur. So, what we need is to synchronize the transaction.

/* The following Java application shows how the transactions in a bank can be carried
out concurrently. */
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science and Engineering

class Account {
public int balance;
public int accountNo;
void displayBalance() {
System.out.println("Account No:" + accountNo + "Balance: " + balance);
}

synchronized void deposit(int amount){


balance = balance + amount;
System.out.println( amount + " is deposited");
displayBalance();
}

synchronized void withdraw(int amount){


balance = balance - amount;
System.out.println( amount + " is withdrawn");
displayBalance();
}
}

class TransactionDeposit implements Runnable{


int amount;
Account accountX;
TransactionDeposit(Account x, int amount){
accountX = x;
this.amount = amount;
new Thread(this).start();
}
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science and Engineering

public void run()


{
accountX.deposit(amount);
}
}

class TransactionWithdraw implements Runnable{


int amount;
Account accountY;

TransactionWithdraw(Account y, int amount) {


accountY = y;
this.amount = amount;
new Thread(this).start();
}

public void run(){


accountY.withdraw(amount);
}
}

class Mythread7{
public static void main(String args[]) {
Account ABC = new Account();
ABC.balance = 1000;
ABC.accountNo = 111;
TransactionDeposit t1;
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science and Engineering

TransactionWithdraw t2;
t1 = new TransactionDeposit(ABC, 500);
t2 = new TransactionWithdraw(ABC,900);
}
}

In the above example, the keyword synchronized is used for the methods void deposite(..) and
void withdraw() so that these two methods will never run for the same object instance
simultaneously.
Alternatively, if one wants to design a class that was not designed for multi-thread access and
thus has non-synchronized methods, then it can be wrapped the call to the methods in a
synchronized block. Here is the general form of the synchronized statement :
synchronized (Object ) { block of statement(s) }
where Object is any object reference. For example, make all the methods in Account class as
non-synchronized (remove the synchronized key word). Then modify the code for run( ) in
class TransactionDeposite and class TransactionWithdraw are as under :
public void run( ) { // in TransactionDeposite
synchronized (accountX ) {
accountX.deposite(amount );
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science and Engineering

}
}

public void run( ) { // in TransactionWithdraw


synchronized (accountY ) {
accountY.withdraw(amount );
}
}
We will get the same output.
Note : In a class, non-synchronized methods are concurrently executable.

Inter-thread Communication
Inter-thread communication in Java is a technique through which multiple threads
communicate with each other. It provides an efficient way through which more than one thread
communicate with each other by reducing CPU idle time. CPU idle time is a process in which
CPU cycles are not wasted.
When more than one threads are executing simultaneously, sometimes they need to
communicate with each other by exchanging information with each other. A thread exchanges
information before or after it changes its state.
There are several situations where communication between threads is important. For example,
suppose that there are two threads A and B. Thread B uses data produced by Thread A and
performs its task.
If Thread B waits for Thread A to produce data, it will waste many CPU cycles. But if threads
A and B communicate with each other when they have completed their tasks, they do not have
to wait and check each other’s status every time.
Thus, CPU cycles will not waste. This type of information exchanging between threads is called
inter thread communication in Java.
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science and Engineering

How to Achieve Inter Thread Communication in Java

Java includes an elegant inter process communication mechanism via the three methods-
1. wait( ),
2. notify( ),
3. notifyAll( )
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( ) or notifyAll( ).

• 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 notify All(

Program code 1:
// In this program, we will understand how to use wait and notify.
// It is the most efficient way for thread communication.
class A
{
int i;
boolean flag = false; // flag will be true when data production is over.
synchronized void deliver(int i)
{
if(flag)
try {
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science and Engineering

wait(); // Wait till a notification is received from Thread2. There will be no wastage of time.

}
catch(InterruptedException ie) {
System.out.println(ie);
}
this.i = i;
flag = true; // When data production is over, it will store true into flag.
System.out.println("Data Delivered: " +i);
notify(); // When data production is over, it will notify Thread2 to use it.
}
synchronized int receive()
{
if(!flag)
try {
wait(); // Wait till a notification is received from Thread1.
}
catch(InterruptedException ie){
System.out.println(ie);
}
System.out.println("Data Received: " + i);
flag = false; // It will store false into flag when data is received.
notify(); // When data received is over, it will notify Thread1 to produce next data.
return i;
}
}
class Thread1 extends Thread
{
A obj;
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science and Engineering

Thread1(A obj)
{
this.obj = obj;
}
public void run()
{
for(int j = 1; j <= 5; j++){
obj.deliver(j);
}
}}
class Thread2 extends Thread
{
A obj;
Thread2(A obj)
{
this.obj = obj;
}
public void run()
{
for(int k = 0; k <= 5; k++) {
obj.receive();
}
}
}
public class Mythread4
{
public static void main(String[] args)
{
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science and Engineering

A obj = new A(); // Creating an object of class A.


// Creating two thread objects and pass reference variable obj as parameter to Thread1 and
Thread2.
Thread1 t1 = new Thread1(obj);
Thread2 t2 = new Thread2(obj);
// Run both threads.
t1.start();
t2.start();
}
}

Program code 2:
// A correct implementation of Producer and Consumer.
class Q
{
int i;
boolean valueSet = false;
synchronized void produce(int i)
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science and Engineering

{
if(valueSet)
try
{
wait();
}
catch(InterruptedException ie)
{
System.out.println(ie);
}
this.i = i;
valueSet = true;
System.out.println("Data Produced: " +i);
notify();
}
synchronized int consume()
{
if(!valueSet)
try {
wait();
}
catch(InterruptedException ie){
System.out.println(ie);
}
System.out.println("Data Consumed: " + i);
valueSet = false;
notify();
return i;
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science and Engineering

}
}
class Producer extends Thread
{
Q q;
Producer(Q q)
{
this.q = q;
}
public void run()
{
for(int j = 1; j <= 5; j++) {
q.produce(j);
}
}
}
class Consumer extends Thread
{
Q q;
Consumer(Q q)
{
this.q = q;
}
public void run()
{
for(int k = 0; k <= 5; k++) {
q.consume();
}
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science and Engineering

}
}
public class Mythread5 {
public static void main(String[] args)
{
Q q = new Q();

Producer p = new Producer(q);


Consumer c = new Consumer(q);
p.start();
c.start();
}
}

You might also like