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

Multithreading in Java

The document provides an overview of multithreading in Java, explaining how to create threads using the Thread class and the Runnable interface. It details the life cycle of a thread, thread priorities, important thread methods, and the need for thread synchronization to prevent concurrency issues. Examples demonstrate both unsynchronized and synchronized thread operations, highlighting the importance of managing shared resources.

Uploaded by

xatiy52541
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
0 views

Multithreading in Java

The document provides an overview of multithreading in Java, explaining how to create threads using the Thread class and the Runnable interface. It details the life cycle of a thread, thread priorities, important thread methods, and the need for thread synchronization to prevent concurrency issues. Examples demonstrate both unsynchronized and synchronized thread operations, highlighting the importance of managing shared resources.

Uploaded by

xatiy52541
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 20

Multithreading in Java

Multithreading is a Java feature that allows the concurrent execution of two or


more parts of a program for maximum utilization of the CPU. Each part of such
a program is called a thread. So, threads are lightweight processes within a
process.
Different Ways to Create Threads
Threads can be created by using two mechanisms:
1. Extending the Thread class
2. Implementing the Runnable Interface
1. By Extending the Thread Class
We create a class that extends the java.lang.Thread class. This class overrides
the run() method available in the Thread class. A thread begins its life inside
the run() method. We create an object of our new class and call
the start() method to start the execution of a thread.start() invokes the run()
method on the Thread object.
Example: Creating a Thread by extending the Thread class.
1
// Java code for thread creation by extending
2
// the Thread class
3
class Multithreading extends Thread {
4
public void run()
5
{
6
try {
7
// Displaying the thread that is running
8
System.out.println(
9
"Thread " + Thread.currentThread().getId()
10
+ " is running");
11
}
12
catch (Exception e) {
13

14
// Throwing an exception
15
System.out.println("Exception is caught");
16
}
17
}
18
}
19

20
// Main Class
21
public class Geeks
22
{
23
public static void main(String[] args)
24
{
25
int n = 8; // Number of threads
26
for (int i = 0; i < n; i++) {
27
Multithreading object
28
= new Multithreading();
29
object.start();
30
}
31
}
32
}

Output
Thread 13 is running
Thread 14 is running
Thread 12 is running
Thread 11 is running
Thread 16 is running
Thread 15 is running
Thread 18 is running
Thread 17 is running

2. By Implementing the Runnable Interface


We create a new class which implements java.lang.Runnable interface and
override run() method. Then we instantiate a Thread object and call start()
method on this object.
Example: Demonstrating the multithreading by implementing the Runnable
interface.
1
// Java code for thread creation by implementing
2
// the Runnable Interface
3
class Multithreading implements Runnable {
4
public void run()
5
{
6
try {
7
// Displaying the thread that is running
8
System.out.println(
9
"Thread " + Thread.currentThread().getId()
10
+ " is running");
11
}
12
catch (Exception e) {
13

14
// Throwing an exception
15
System.out.println("Exception is caught");
16
}
17
}
18
}
19

20
// Main Class
21
class Geeks {
22
public static void main(String[] args)
23
{
24
int n = 8; // Number of threads
25
for (int i = 0; i < n; i++) {
26
Thread object
27
= new Thread(new Multithreading());
28
object.start();
29
}
30
}
31
}

Output
Thread 12 is running
Thread 15 is running
Thread 18 is running
Thread 11 is running
Thread 17 is running
Thread 13 is running
Thread 16 is running
Thread 14 is running
Thread Class vs Runnable Interface

Aspect Thread Class Runnable Interface

We need to extend a Thread It is a interface so use


class. Because it is a class. It using the implent
means we can not add any keyword and allows us to
Inheritance other class if we extend it. use other classes as well.

The Thread object cannot be The object of Runnable


sharing among the different interface can be shared
Thread Sharing multiple threads. among different threads.

We can override the run() We can implement the


method present in the Thread run() method present in
Implementation class. the Runnable interface.

It provides methods like These methods are not


yield(), interrupt() and getId present in the Runnable
Built-in Methods etc. interface .

Life Cycle of a Thread in Java Multithreading


A thread goes through various stages in its life cycle. For example, a thread is
born, started, runs, and then dies. The following diagram shows the complete
life cycle of a thread.
Following are the stages of the life cycle −
 New − A new thread begins its life cycle in the new state. It remains in
this state until the program starts the thread. It is also referred to as
a born thread.
 Runnable − After a newly born thread is started, the thread becomes
runnable. A thread in this state is considered to be executing its task.
 Waiting − Sometimes, a thread transitions to the waiting state while the
thread waits for another thread to perform a task. A thread transitions
back to the runnable state only when another thread signals the waiting
thread to continue executing.
 Timed Waiting − A runnable thread can enter the timed waiting state for
a specified interval of time. A thread in this state transitions back to the
runnable state when that time interval expires or when the event it is
waiting for occurs.
 Terminated (Dead) − A runnable thread enters the terminated state when
it completes its task or otherwise terminates.
Thread Priorities
Every Java thread has a priority that helps the operating system determine the
order in which threads are scheduled.
Java thread priorities are in the range between MIN_PRIORITY (a constant of
1) and MAX_PRIORITY (a constant of 10). By default, every thread is given
priority NORM_PRIORITY (a constant of 5).
Threads with higher priority are more important to a program and should be
allocated processor time before lower-priority threads. However, thread
priorities cannot guarantee the order in which threads execute and are very
much platform dependent.
Thread Methods
Following is the list of important methods available in the Thread class.

Sr.No
Method & Description
.

public void start()


1 Starts the thread in a separate path of execution, then invokes the
run() method on this Thread object.

public void run()


2 If this Thread object was instantiated using a separate Runnable
target, the run() method is invoked on that Runnable object.

public final void setName(String name)


3 Changes the name of the Thread object. There is also a getName()
method for retrieving the name.

public final void setPriority(int priority)


4 Sets the priority of this Thread object. The possible values are
between 1 and 10.

public final void setDaemon(boolean on)


5
A parameter of true denotes this Thread as a daemon thread.

public final void join(long millisec)

6 The current thread invokes this method on a second thread,


causing the current thread to block until the second thread
terminates or the specified number of milliseconds passes.

7 public void interrupt()


Interrupts this thread, causing it to continue execution if it was
blocked for any reason.

public final boolean isAlive()


8 Returns true if the thread is alive, which is any time after the
thread has been started but before it runs to completion.

The previous methods are invoked on a particular Thread object. The following
methods in the Thread class are static. Invoking one of the static methods
performs the operation on the currently running thread.

Sr.No
Method & Description
.

public static void yield()


1 Causes the currently running thread to yield to any other threads
of the same priority that are waiting to be scheduled.

public static void sleep(long millisec)


2 Causes the currently running thread to block for at least the
specified number of milliseconds.

public static boolean holdsLock(Object x)


3 Returns true if the current thread holds the lock on the given
Object.

public static Thread currentThread()


4 Returns a reference to the currently running thread, which is the
thread that invokes this method.

public static void dumpStack()


5 Prints the stack trace for the currently running thread, which is
useful when debugging a multithreaded application.

Example
The following ThreadClassDemo program demonstrates some of these methods
of the Thread class. Consider a class DisplayMessage which
implements Runnable −
// File Name : DisplayMessage.java
// Create a thread to implement Runnable

public class DisplayMessage implements Runnable {


private String message;

public DisplayMessage(String message) {


this.message = message;
}

public void run() {


while(true) {
System.out.println(message);
}
}
}
Following is another class which extends the Thread class −
// File Name : GuessANumber.java
// Create a thread to extentd Thread

public class GuessANumber extends Thread {


private int number;
public GuessANumber(int number) {
this.number = number;
}
public void run() {
int counter = 0;
int guess = 0;
do {
guess = (int) (Math.random() * 100 + 1);
System.out.println(this.getName() + " guesses " + guess);
counter++;
} while(guess != number);
System.out.println("** Correct!" + this.getName() + "in" + counter +
"guesses.**");
}
}
Following is the main program, which makes use of the above-defined classes −
Open Compiler
// File Name : ThreadClassDemo.java
public class ThreadClassDemo {

public static void main(String [] args) {


Runnable hello = new DisplayMessage("Hello");
Thread thread1 = new Thread(hello);
thread1.setDaemon(true);
thread1.setName("hello");
System.out.println("Starting hello thread...");
thread1.start();

Runnable bye = new DisplayMessage("Goodbye");


Thread thread2 = new Thread(bye);
thread2.setPriority(Thread.MIN_PRIORITY);
thread2.setDaemon(true);
System.out.println("Starting goodbye thread...");
thread2.start();

System.out.println("Starting thread3...");
Thread thread3 = new GuessANumber(27);
thread3.start();
try {
thread3.join();
} catch (InterruptedException e) {
System.out.println("Thread interrupted.");
}
System.out.println("Starting thread4...");
Thread thread4 = new GuessANumber(75);

thread4.start();
System.out.println("main() is ending...");
}
}
class DisplayMessage implements Runnable {
private String message;

public DisplayMessage(String message) {


this.message = message;
}

public void run() {


while(true) {
System.out.println(message);
}
}
}
class GuessANumber extends Thread {
private int number;
public GuessANumber(int number) {
this.number = number;
}

public void run() {


int counter = 0;
int guess = 0;
do {
guess = (int) (Math.random() * 100 + 1);
System.out.println(this.getName() + " guesses " + guess);
counter++;
} while(guess != number);
System.out.println("** Correct!" + this.getName() + "in" + counter +
"guesses.**");
}
}
Output
Starting hello thread...
Starting goodbye thread...
Hello
Hello
Hello
Hello
Hello
Hello
Goodbye
Goodbye
Goodbye
Goodbye
Goodbye
.......
Need of Thread Synchronization?
When we start two or more threads within a program, there may be a situation
when multiple threads try to access the same resource and finally they can
produce unforeseen result due to concurrency issues. For example, if multiple
threads try to write within a same file then they may corrupt the data because
one of the threads can override data or while one thread is opening the same file
at the same time another thread might be closing the same file.
So there is a need to synchronize the action of multiple threads and make sure
that only one thread can access the resource at a given point in time. This is
implemented using a concept called monitors. Each object in Java is associated
with a monitor, which a thread can lock or unlock. Only one thread at a time
may hold a lock on a monitor.
Thread Synchronization in Java
Java programming language provides a very handy way of creating threads and
synchronizing their task by using synchronized blocks. You keep shared
resources within this block. Following is the general form of the synchronized
statement −
Syntax
synchronized(objectidentifier) {
// Access shared variables and other shared resources
}
Here, the objectidentifier is a reference to an object whose lock associates with
the monitor that the synchronized statement represents. Now we are going to
see two examples, where we will print a counter using two different threads.
When threads are not synchronized, they print counter value which is not in
sequence, but when we print counter by putting inside synchronized() block,
then it prints counter very much in sequence for both the threads.
Multithreading Example without Thread Synchronization
Here is a simple example which may or may not print counter value in sequence
and every time we run it, it produces a different result based on CPU
availability to a thread.
Example
Open Compiler
class PrintDemo {
public void printCount() {
try {
for(int i = 5; i > 0; i--) {
System.out.println("Counter --- " + i );
}
} catch (Exception e) {
System.out.println("Thread interrupted.");
}
}
}

class ThreadDemo extends Thread {


private Thread t;
private String threadName;
PrintDemo PD;

ThreadDemo( String name, PrintDemo pd) {


threadName = name;
PD = pd;
}

public void run() {


PD.printCount();
System.out.println("Thread " + threadName + " exiting.");
}

public void start () {


System.out.println("Starting " + threadName );
if (t == null) {
t = new Thread (this, threadName);
t.start ();
}
}
}

public class TestThread {


public static void main(String args[]) {

PrintDemo PD = new PrintDemo();

ThreadDemo T1 = new ThreadDemo( "Thread - 1 ", PD );


ThreadDemo T2 = new ThreadDemo( "Thread - 2 ", PD );

T1.start();
T2.start();
// wait for threads to end
try {
T1.join();
T2.join();
} catch ( Exception e) {
System.out.println("Interrupted");
}
}
}
This produces a different result every time you run this program −
Output
Starting Thread - 1
Starting Thread - 2
Counter --- 5
Counter --- 4
Counter --- 3
Counter --- 5
Counter --- 2
Counter --- 1
Counter --- 4
Thread Thread - 1 exiting.
Counter --- 3
Counter --- 2
Counter --- 1
Thread Thread - 2 exiting.
Multithreading Example with Thread Synchronization
Here is the same example which prints counter value in sequence and every
time we run it, it produces the same result.
Example
Open Compiler
class PrintDemo {
public void printCount() {
try {
for(int i = 5; i > 0; i--) {
System.out.println("Counter --- " + i );
}
} catch (Exception e) {
System.out.println("Thread interrupted.");
}
}
}

class ThreadDemo extends Thread {


private Thread t;
private String threadName;
PrintDemo PD;

ThreadDemo( String name, PrintDemo pd) {


threadName = name;
PD = pd;
}

public void run() {


synchronized(PD) {
PD.printCount();
}
System.out.println("Thread " + threadName + " exiting.");
}

public void start () {


System.out.println("Starting " + threadName );
if (t == null) {
t = new Thread (this, threadName);
t.start ();
}
}
}

public class TestThread {

public static void main(String args[]) {


PrintDemo PD = new PrintDemo();

ThreadDemo T1 = new ThreadDemo( "Thread - 1 ", PD );


ThreadDemo T2 = new ThreadDemo( "Thread - 2 ", PD );

T1.start();
T2.start();

// wait for threads to end


try {
T1.join();
T2.join();
} catch ( Exception e) {
System.out.println("Interrupted");
}
}
}
This produces the same result every time you run this program −
Output
Starting Thread - 1
Starting Thread - 2
Counter --- 5
Counter --- 4
Counter --- 3
Counter --- 2
Counter --- 1
Thread Thread - 1 exiting.
Counter --- 5
Counter --- 4
Counter --- 3
Counter --- 2
Counter --- 1
Thread Thread - 2 exiting.

You might also like