0% found this document useful (0 votes)
73 views

Threads Notes

The document discusses threads in Java including their life cycle, how to create threads by implementing Runnable interface and extending Thread class, identifying thread priorities, thread synchronization and inter-thread communication. It also covers thread states, methods like start(), run(), join() and isAlive().
Copyright
© © All Rights Reserved
Available Formats
Download as PPS, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
73 views

Threads Notes

The document discusses threads in Java including their life cycle, how to create threads by implementing Runnable interface and extending Thread class, identifying thread priorities, thread synchronization and inter-thread communication. It also covers thread states, methods like start(), run(), join() and isAlive().
Copyright
© © All Rights Reserved
Available Formats
Download as PPS, PDF, TXT or read online on Scribd
You are on page 1/ 34

Threads

Pre-assessment Questions
1. Which package defines classes that implement GUI, such as buttons,
checkboxes, and comboboxes ?
a. java.applet
b. java.io
c. java.awt
d. java.net
2. Which class of the java.lang package provides methods for converting
characters from uppercase to lowercase?
a. System
b. Character
c. Object
d. Class

NIIT

Packages and Streams

Lesson 1B / Slide 1 of 25

Threads

Pre-assessment Questions (Contd.)


3. Which method returns the largest double value of the next smaller integer?
a. floor()
b. ceil()
c. abs()
d. round()
4. Which method copies characters from a source String object into the
destination character array?
a. getChars()
b. charAt()
c. compareTo()
d. length()

NIIT

Packages and Streams

Lesson 1B / Slide 2 of 25

Threads

Pre-assessment Questions (Contd.)


5. Identify the correct order of steps to be taken to create a user-defined
package:
1.
Create a source file containing the package definition.
2.
Compile the source file.
3.
Create a folder having the same name as package name and save the
source file within the folder.
a.
b.
c.
d.

NIIT

1,
1,
2,
3,

2,
3,
3,
2,

3
2
1
1

Packages and Streams

Lesson 1B / Slide 3 of 25

Threads

Solutions to Pre-assessment
Questions
1.
2.
3.
4.
5.

NIIT

c.
b.
a.
a.
b.

java.awt
Character
floor()
getChars()
1, 3, 2

Packages and Streams

Lesson 1B / Slide 4 of 25

Threads

Objectives

NIIT

In this lesson, you will learn about:


Using threads in Java
The life cycle of a thread
Creating threads
Identifying the thread priorities
Thread synchronization and inter-threaded communication
Garbage collection

Packages and Streams

Lesson 1B / Slide 5 of 25

Threads

Using Threads in Java

A thread is defined as the of execution of a program.


For example, a Central Processing Unit (CPU) performs various tasks
simultaneously, such as writing and printing a document, installing a software,
and displaying the date and time on the status bar. All these processes are
handled by separate threads.
A process that is made of one thread is known as single-threaded process.

A process that creates two or more threads is called a multithreaded process.

NIIT

Packages and Streams

Lesson 1B / Slide 6 of 25

Threads

Using Threads in Java (Contd.)

NIIT

Basic Concepts of multithreading


Multitasking is the ability to execute more than one task at the same time.
Multitasking can be divided into two categories:
Process-based multitasking
Thread-based multitasking
Benefits of multithreading
Improved performance
Minimized system resource usage
Simultaneous access to multiple applications
Program structure simplification
Pitfalls of multithreading
Race condition
Deadlock condition
Lock starvation
Packages and Streams

Lesson 1B / Slide 7 of 25

Threads

Using Threads in Java (Contd.)

NIIT

The Thread class


The java.lang.Thread class is used to construct and access individual threads
in a multithreaded application.
The Thread class contains various methods that can obtain information
about the activities of a thread, such as setting and checking the properties
of a thread, causing a thread to wait, and being interrupted or destroyed.
A few methods defined in the Thread class are:
currentThread(): To know the currently running thread.
setName(): To set the name to the thread.
getName(): Returns the name of the thread.
setPriority(): To set the priority to a thread.
getPriority(): Returns the priority of a thread.
isAlive(): Determines whether a thread is running.
sleep(): Makes the thread to pause for a period of time.
wait(): Makes the thread to pause for a period of time.
Packages and Streams

Lesson 1B / Slide 8 of 25

Threads

Using Threads in Java (Contd.)

NIIT

join(): To wait till a thread dies


start(): Starts a thread by calling the run() method.
run(): It runs the Thread

The first thread to be executed in a multithreaded process is called the


main thread. The main thread is created automatically on the start up of
Java program execution.

Packages and Streams

Lesson 1B / Slide 9 of 25

Threads

The Life-cycle of a Thread

NIIT

The various states in the life cycle of a thread are:


New
Runnable
Not Runnable
Terminated or Dead
The following figure shows the life-cycle of a thread:

Packages and Streams

Lesson 1B / Slide 10 of 25

Threads

Creating Threads

You can create a thread in the following ways:


Implementing Runnable interface
Extending the Thread class
Creating Threads by implementing the Runnable interface
The Runnable interface only consists of the run() method, which is
executed when the thread is activated.
When a program needs to inherit from a class other than from the Thread
class, you need to implement the Runnable interface.
The following syntax shows how to declare the run() method:
public void run()

NIIT

You can use the following code to create a thread by implementing the
Runnable interface:
class NewThread implements Runnable
{
Thread t;
NewThread()
{
Packages and Streams

Lesson 1B / Slide 11 of 25

Threads

Creating Threads (Contd.)


t = new Thread(this, "ChildThread");
System.out.println("Child Thread:" + t);
t.start();
}
public void run()
{ // Implementing the run() method of the Runnable interface
System.out.println("Child Thread Started");
System.out.println("Exiting the child thread");
}
}
class ThreadClass
{
public static void main(String args[])
{
new NewThread();
System.out.println("Main thread Started");

NIIT

Packages and Streams

Lesson 1B / Slide 12 of 25

Threads

Creating Threads (Contd.)


try
{
Thread.sleep(5000);
}
catch(InterruptedException e)
{
System.out.println("The main thread interrupted");}
System.out.println("Exiting the main thread");
}
}

NIIT

Packages and Streams

Lesson 1B / Slide 13 of 25

Threads

Creating Threads (Contd.)

NIIT

Creating Threads by extending the Thread class


The class extending the Thread class calls the start() method to begin
the child thread execution.
You can use the following code to create a thread by extending the
Thread class:
class ThreadDemo extends Thread
{
ThreadDemo()
{
super("ChildThread"); // calls the superclass constructor
System.out.println("ChildThread:" + this);
start();
}

Packages and Streams

Lesson 1B / Slide 14 of 25

Threads

Creating Threads (Contd.)


public void run()
{
System.out.println("The child thread started");
System.out.println("Exiting the child thread");
}
}
class ThreadDemoClass
{
public static void main(String args[])
{
new ThreadDemo();
System.out.println("The main thread started");
System.out.println("The main thread sleeping");

NIIT

Packages and Streams

Lesson 1B / Slide 15 of 25

Threads

Creating Threads (Contd.)


try
{
Thread.sleep(1000);
}
catch(InterruptedException e)
{
System.out.println("The main thread
interrupted");
}
System.out.println("Exiting main thread");
})
NIIT

Packages and Streams

Lesson 1B / Slide 16 of 25

Threads

Creating Threads (Contd.)


Creating Multiple threads
You can create multiple threads in a program by implementing the

Runnable interface or extending the Thread class.


Using the isAlive() Method
The isAlive() method is used to check the existence of a
thread.
The following syntax shows how to declare the isAlive()
method:
public final boolean isAlive()

Using the join() Method


It is called the join() method because the thread calling the
join() method waits until the specified thread joins the calling
method.
The following syntax shows how to declare the join() method:
public final void join() throws InterruptedException
NIIT

Packages and Streams

Lesson 1B / Slide 17 of 25

Threads

Identifying the Thread Priorities

The Java Run-time Environment executes threads based on their priority.


A CPU can execute only one thread at a time. Therefore, the threads, which are
ready for execution, queue up for their turn to get executed by the processor.
A thread with higher priority runs before threads with low priority.
Defining Thread Priority
Thread priorities are the integers in the range of 1 to 10 that specify the priority
of one thread with respect to the priority of another thread.
The threads are scheduled using fixed priority scheduling.
The Java Run-time system selects the runnable thread with the highest priority
of execution when a number of threads get ready to execute.
Setting the Thread Priority
You can set the thread priority after it is created using the setPriority() method
declared in the Thread class.
The following syntax shows how to declare the setPriority() method:
public final void setPriority(int newPriority)
NIIT

Packages and Streams

Lesson 1B / Slide 18 of 25

Threads

Thread Synchronization and


Interthread Communication

NIIT

When two threads need to share data, you must ensure that one thread does
not change the data used by the other thread.
Synchronizing Threads
Synchronization of threads ensures that if two or more threads need to
access a shared resource then that resource is used by only one thread
at a time.
Synchronization is based on the concept of monitor.
The monitor controls the way in which synchronized methods access an
object or class.
To enter an objects monitor, you need to call a synchronized method.
When a thread calls the wait() method, it temporarily releases the locks
that it holds. In addition, the thread stops running and is added to the
list of waiting threads for that object.
Packages and Streams

Lesson 1B / Slide 19 of 25

Threads

Thread Synchronization and


Interthread Communication (Contd.)
The following figure shows the synchronization of threads:

NIIT

Packages and Streams

Lesson 1B / Slide 20 of 25

Threads

Thread Synchronization and


Interthread Communication (Contd.)

NIIT

Communication Across Threads


A thread may notify another thread that the task has been completed.
This communication between threads is known as interthread
communication.
The various methods used in interthread communication are:
wait()
notify()
notifyAll()

Packages and Streams

Lesson 1B / Slide 21 of 25

Threads

Deadlock Conditions

Deadlock conditions occur in an application where multiple threads need to access


multiple resources.
Deadlocks occur when two threads have a circular dependency on a pair of
synchronized objects.

NIIT

Collaborate

Lesson 1C / Slide 22 of 20

Threads

Deadlock Conditions (Contd.)

The precautions required to avoid deadlocks are:


Deciding the order of the locking objects and adhering to that order.
Releasing the locks in the reverse order.

NIIT

Collaborate

Lesson 1C / Slide 23 of 20

Threads

setDaemon() Method

A daemon thread is a thread that runs in the background of a program and


provides services to other threads.
The daemon threads are background service providers for other threads.
For example, garbage collector, clock handler, and the screen updater threads are
the daemon threads.
The Java interpreter terminates its execution when only daemon threads are left in
the program.
The setDaemon() method is used to convert a thread to a daemon thread.
The following syntax shows how to set a thread, Thread1 as a daemon thread:
Thread1.setDaemon(true);
The daemon thread is a part of the Java run-time system and does not belong to
any particular program.

NIIT

Collaborate

Lesson 1C / Slide 24 of 20

Threads

Garbage Collection

NIIT

Garbage collection is the feature of Java that helps to automatically destroy


the objects created and release their memory for future reallocation.
The various activities involved in garbage collection are:
Monitoring the objects used by a program and determining when they
are not in use.
Destroying objects that are no more in use and reclaiming their
resources, such as memory space.
The Java Virtual machine (JVM) acts as the garbage collector that keeps
a track of the memory allocated to various objects and the objects being
referenced.
The various methods of the Runtime class used in memory management
are:
static Runtime getRuntime(): Returns the current runtime object.
void gc(): Invokes garbage collection.
long totalMemory(): Returns the total number of bytes of memory
available in JVM.

Packages and Streams

Lesson 1B / Slide 25 of 25

Threads
Implementing Garbage Collection

You can explicitly run the garbage collector in Java to collect information
regarding how large the object heap is or to determine the number of objects
of a certain type that can be instantiated.

To obtain these values, you can use the totalMemory() and freeMemory()
methods.
The totalMemory() method returns the total memory in the JVM, and
The freeMemory() returns the amount of memory free in the JVM.

To run the garbage collector explicitly, you need to perform the following
steps:
Create an object of the Runtime class.
Runtime r = Runtime.getRuntime();

NIIT

Invoke the gc() method of the Runtime class


r.gc();

Packages and Streams

Lesson 1B / Slide 26 of 25

Threads

Best Practices
The join() Method

NIIT

It is a good programming practice to use the join() method in order to


ensure that the main thread is the last thread to be executed in a program.
The join() method is called for each child thread within the main thread. This
causes the main thread to wait until all the child threads are terminated.

Collaborate

Lesson 1C / Slide 27 of 20

Threads

Tips and Tricks


Threading

NIIT

When you have two tasks within a program that can execute independently,
make individual threads for them.

Collaborate

Lesson 1C / Slide 28 of 20

Threads

FAQs

The two approaches to create threads are by implementing the Runnable


interface and by extending the Thread class. Which of these two approaches
is better and why?
The two approaches to create a thread are by implementing the Runnable
interface and by extending the Thread class. The Thread class defines the
various methods that can be overriden by a derived class. It is advisableto
extend a class when it is being enhanced or modified in some way. If you are
not overriding any of the methods of the Thread class other than the run()
method, then it is recommended to implement the Runnable interface.
In addition, Java does not support multiple inheritance. Applets extend from
the Applet class. You cannot inherit from both the Applet and Thread class.
The Runnable interface consists only of the run()method , which is executed
when the thread is activated. You can extend from the Applet class,
implement the Runnable interface and code the run() method. Therefore,
when a program needs to inherit from a class apart from the Thread class,
you need to implement the Runnable interface.

NIIT

Collaborate

Lesson 1C / Slide 29 of 20

Threads

FAQs (Contd.)

Which interface is extended to implement threads?


All threads implement the Runnable interface. The Runnable interface
contains the run() method which is needed to start a thread.

How do you ensure that your threads share the processor of the computer
properly?
To ensure that all the threads share the memory of the processor properly,
call the yield() or sleep() method in the thread. The sleep() method is used
to keep the thread in the sleeping mode for a specified time. The yield()
method is used to allocate processor time to a low priority thread.

NIIT

Collaborate

Lesson 1C / Slide 30 of 20

Threads

Demonstration-Implementing
Threads in Java

Problem Statement

Solution

NIIT

The current date and time has to be displayed on the status


bar of the Applicants details applet.

The Java application is created that displays the current date


and time on the status bar of an applet.
To solve the above problem, perform the following tasks:
1. Create the code and the html file for the application.
2. Compile and execute the application.
Packages and Streams

Lesson 1B / Slide 31 of 25

Threads

Summary
In this lesson, you learned:
A thread is defined as the path of execution of a program. It is a sequence of
instructions that is executed to define a unique flow of control.
A program that creates two or more threads is called a multithreaded
program.
The two types of multitasking are:
Process-based
Thread-based
The various advantages of multithreading are:
Improved Performance
Minimized System Resources Usage
Simultaneous access to multiple applications

NIIT

Packages and Streams

Lesson 1B / Slide 32 of 25

Threads

Summary (Contd.)

NIIT

The various disadvantages of multithreading are:


Race condition
Deadlock
Lock starvation
The java.lang.Thread class is used to construct and access individual threads
in a multithreaded application.
The various states in the life cycle of a thread are:
New
Runnable
Not Runnable
Terminated or Dead
You can create a thread in the following ways:
Implementing Runnable interface
Extending the Thread class
Packages and Streams

Lesson 1B / Slide 33 of 25

Threads

Summary(Contd.)

NIIT

Thread priorities are the integers in the range of 1 to 10 that specify the
priority of one thread with respect to the priority of another thread.
You can set the thread priority after it is created using the setPriority()
method declared in the Thread class.
Synchronization of threads ensures that if two or more threads need to
access a shared resource, the resource is used by only one thread at a
time.
Various threads can communicate with each other using the following
methods:
wait()
notify()
notifyAll()
Garbage collection is the feature of Java that helps to automatically
destroy the objects created and release their memory for future
reallocation.
Packages and Streams

Lesson 1B / Slide 34 of 25

You might also like