0% found this document useful (0 votes)
4 views51 pages

Threads

The document provides an overview of Java multithreading, including the definition of threads, their life cycle, and methods for creating and managing them. It discusses the advantages of multithreading, thread synchronization, and potential issues such as race conditions and memory inconsistency errors. Additionally, it covers thread priorities and provides examples of implementing threads in Java.

Uploaded by

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

Threads

The document provides an overview of Java multithreading, including the definition of threads, their life cycle, and methods for creating and managing them. It discusses the advantages of multithreading, thread synchronization, and potential issues such as race conditions and memory inconsistency errors. Additionally, it covers thread priorities and provides examples of implementing threads in Java.

Uploaded by

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

ASET

Amity School of Engineering &


Technology

Java Multithreading

1
Objectives ASET

After completing this section, students will be able to


 Understand Threads in Java and their use
 Create multithreaded programs
 Use synchronized methods or blocks to
synchronize threads

2
Contents ASET

1. What is a Thread ?
2. Creating, Implementing and Extending a Thread
3. The life-cycle of a Thread
4. Interrupt a Thread
5. Thread synchronization
What is a Thread ? ASET

• A sequential (or single-threaded) program is one


that, when executed, has only one single flow of
control.
– i.e., at any time instant, there is at most only one
instruction (or statement or execution point) that
is being executed in the program.
Multitasking ASET

• Multitasking is a process of executing multiple


tasks simultaneously. We use multitasking to
utilize the CPU. Multitasking can be achieved
in two ways:
• Process-based Multitasking (Multiprocessing)

• Thread-based Multitasking (Multithreading)


Process-based Multitasking ASET

(Multiprocessing)
• Each process has an address in memory. In
other words, each process allocates a separate
memory area.
• A process is heavy weight.
• Cost of communication between the process is
high.
• Switching from one process to another requires
some time for saving and loading registers,
memory maps, updating lists, etc.
Thread-based Multitasking ASET

(Multithreading)

• Threads share the same address space.


• A thread is lightweight.
• Cost of communication between the thread is
low.
Multithreading in Java ASET

• Multithreading in Java is a process of


executing multiple threads simultaneously.

• A thread is a light weight sub-process, the


smallest unit of processing.
Advantages of Java Multithreading ASET

• 1) It doesn't block the user because threads are


independent and you can perform multiple
operations at the same time.

• 2) You can perform many operations together,


so it saves time.

• 3) Threads are independent, so it doesn't affect


other threads if an exception occurs in a single
thread.
Life cycle of a Thread ASET

These states are:


•1. Newborn State
2. Runnable State
3. Running State
4. Blocked State
5. Dead State
Life cycle of a Thread ASET
Life cycle of a Thread ASET
ASET

Newborn State:
When we want to create a thread object,
the thread is born then it is said to be Newborn
State.
At this State, we can do by using start() method.
Active: When a thread invokes the start()
method,
it moves from the new state to the active state.
The active state contains two states within it:
one is runnable, and the other is running.
Life cycle of a Thread ASET

Blocked or Waiting: Whenever a thread is


inactive for a span of time (not permanently)
then, either the thread is in the blocked state or
is in the waiting state
Dead: A thread reaches the termination state
because of the following reasons:
When a thread has finished its job, then it exists
or terminates normally.
Abnormal termination: It occurs when some
unusual events such as an unhandled exception
or segmentation fault.
How to create a thread in Java ASET

There are two ways to create a thread:


•By extending Thread class
•By implementing Runnable interface.
Thread Class ASET

• Thread class provide constructors and methods to


create and perform operations on a thread. Thread
class extends Object class and implements Runnable
interface.
• Commonly used Constructors of Thread class:
• Thread()
• Thread(String name)
• Thread(Runnable r)
• Thread(Runnable r,String name)

16
Methods of Thread class: ASET
• public void run(): is used to perform action for a thread.
• public void start(): starts the execution of the thread.JVM
calls the run() method on the thread.
• public void sleep(long miliseconds): Causes the
currently executing thread to sleep (temporarily cease
execution) for the specified number of milliseconds.
• public void join(): waits for a thread to die.
• public void join(long miliseconds): waits for a thread to
die for the specified miliseconds.
• public int getPriority(): returns the priority of the thread.
• public int setPriority(int priority): changes the priority of
the thread.
• public String getName(): returns the name of the thread.
• public void setName(String name): changes the name of
the thread.
Methods of Thread class: ASET
• public Thread currentThread(): returns the reference of currently
executing thread.
• public int getId(): returns the id of the thread.
• public Thread.State getState(): returns the state of the thread.
• public boolean isAlive(): tests if the thread is alive.
• public void yield(): causes the currently executing thread object to
temporarily pause and allow other threads to execute.
• public void suspend(): is used to suspend the thread(depricated).
• public void resume(): is used to resume the suspended
thread(depricated).
• public void stop(): is used to stop the thread(depricated).
• public void interrupt(): interrupts the thread.
• public boolean isInterrupted(): tests if the thread has been
interrupted.
• public static boolean interrupted(): tests if the current thread has
Runnable interface: ASET
• The Runnable interface should be implemented by
any class whose instances are intended to be
executed by a thread. Runnable interface have only
one method named run().
• public void run(): is used to perform action for a
thread.
• Starting a thread:
• The start() method of Thread class is used to start a
newly created thread. It performs the following tasks:
• A new thread starts(with new callstack).
• The thread moves from New state to the Runnable
state.
• When the thread gets a chance to execute, its target
run() method will run.
thread is running...

Java Thread Example by extending ASET


Thread class
class Multi extends Thread{
public void run(){
System.out.println("thread is running...");
}
public static void main(String args[]){
Multi t1=new Multi();
t1.start();
}
}
thread is running...

Java Thread Example by implementing ASET


Runnable interface
class Multi3 implements Runnable{
public void run(){
System.out.println("thread is running...");
}
public static void main(String args[]){
Multi3 m1=new Multi3();
Thread t1 =new Thread(m1);
// Using the constructor Thread(Runnable r)
t1.start();
}
}
Using the Thread Class: Thread(String
thread is running...

Name) ASET

public class MyThread1


{
public static void main(String argvs[])
{
// creating an object of the Thread class using the constructor Thread(String n
ame)
Thread t= new Thread("My first thread");
// the start() method moves the thread to the active state
t.start();
// getting the thread name by invoking the getName() method
String str = t.getName();
System.out.println(str);
}
}
Using the Thread Class: Thread
thread is running...

(Runnable r, String name) ASET

public class MyThread2 implements Runnable


{ public void run()
{ System.out.println("Now the thread is running ...");
} public static void main(String argvs[])
{ // creating an object of the class MyThread2
MyThread2 r1 = new MyThread2();
// creating an object of the class Thread using Thread(Runnable r, String name)
Thread th1 = new Thread(r1, "My new thread");
// the start() method moves the thread to the active state
th1.start();
// getting the thread name by invoking the getName() method
String str = th1.getName();
System.out.println(str);
} }
Example of the sleep() method in Java
thread is running...

ASET

class TestSleepMethod1 extends Thread{


public void run(){
for(int i=1;i<5;i++){
// the thread will sleep for the 500 milli seconds
try{ Thread.sleep(500); }
catch(InterruptedException e){ System.out.println(e); }
System.out.println(i);
} }
public static void main(String args[]){
TestSleepMethod1 t1=new TestSleepMethod1();
TestSleepMethod1 t2=new TestSleepMethod1();
t1.start();
t2.start();
}
}
ASET

• sleep() Method in Java: When the sleeping


time is -ive
• throws the exception
IllegalArguementException when the time for
sleeping is negative.
• Can we start a thread twice(Exception in
thread "main"
java.lang.IllegalThreadStateException)
Example of naming a thread : Using setName() Method
ASET
class TestMultiNaming1 extends Thread{
public void run(){
System.out.println("running...");
}
public static void main(String args[]){
TestMultiNaming1 t1=new TestMultiNaming1();
TestMultiNaming1 t2=new TestMultiNaming1();
System.out.println("Name of t1:"+t1.getName());
System.out.println("Name of t2:"+t2.getName());
t1.start();
t2.start();
t1.setName(“java user");
System.out.println("After changing name of t1:"+t1.getName());
}
}
What if we call Java run() method directly
instead start() method? ASET

class TestCallRun2 extends Thread{


public void run(){
for(int i=1;i<5;i++){
try{Thread.sleep(500);}
catch(InterruptedException e)
{System.out.println(e);}
System.out.println(i);
} }
public static void main(String args[]){
TestCallRun2 t1=new TestCallRun2();
TestCallRun2 t2=new TestCallRun2();
t1.run();
t2.run();
}
}
Priority of a Thread (Thread Priority)
ASET

Each thread has a priority. Priorities are


represented by a number between 1 and 10. In
most cases, the thread scheduler schedules the
threads according to their priority (known as
preemptive scheduling).
But it is not guaranteed because it depends on JVM
specification that which scheduling it chooses. Note
that not only JVM a Java programmer can also
assign the priorities of a thread explicitly in a Java
program.
Priority of a Thread (Thread Priority)
ASET

Setter & Getter Method of Thread Priority


public final int getPriority():
The java.lang.Thread.getPriority() method returns the priority of the
given thread.

public final void setPriority(int newPriority):


The java.lang.Thread.setPriority() method updates or assign the
priority of the thread to newPriority.
The method throws IllegalArgumentException if the value
newPriority goes out of the range, which is 1 (minimum) to 10
(maximum).
Priority of a Thread (Thread Priority)
ASET

3 constants defined in Thread class:


public static int MIN_PRIORITY
public static int NORM_PRIORITY
public static int MAX_PRIORITY

Default priority of a thread is 5 (NORM_PRIORITY).

The value of MIN_PRIORITY is 1 and the value of


MAX_PRIORITY is 10.
Thread Priority Example
ASET

// Importing the required classes


import java.lang.*;
public class ThreadPriorityExample extends Thread
{
public void run()
{
System.out.println("Inside the run() method");
}
public static void main(String argvs[])
{
ThreadPriorityExample th1 = new ThreadPriorityExample();
ThreadPriorityExample th2 = new ThreadPriorityExample();
ThreadPriorityExample th3 = new ThreadPriorityExample();
System.out.println("Priority of the thread th1 is : " + th1.getPriority());
System.out.println("Priority of the thread th2 is : " + th2.getPriority());
System.out.println("Priority of the thread th2 is : " + th2.getPriority());
Thread Priority Example
ASET

th1.setPriority(6);
th2.setPriority(3);
th3.setPriority(9);
System.out.println("Priority of the thread th1 is : " + th1.getPriority());
System.out.println("Priority of the thread th2 is : " + th2.getPriority());
System.out.println("Priority of the thread th3 is : " + th3.getPriority());

System.out.println("Currently Executing The Thread : " + Thread.currentThrea


d().getName());
}
}
Problems associated with threads
ASET

• Multithreading enables us to better utilize the system’s


resources, but we need to take special care while reading and
writing data shared by multiple threads.

• Two types of problems arise when multiple threads try to


read and write shared data concurrently .

1. Thread interference errors


2. Memory consistency errors
Thread interference errors
(Race Conditions) ASET

• Output depends on the sequence of events. When events do not


occur in the sequence as developer want, it is called race condition.

• Race condition in Java occurs in a multi-threaded


environment when more than one thread try to access a shared
resource (modify, write) at the same time.

• It is safe if multiple threads are trying to read a shared resource as


long as they are not trying to change it.

• Multiple threads executing inside a method is not a problem in


itself, problem arises when these threads try to access the same
resource(class variables, DB record in a table, writing in a file).
ASET

Race Conditions
Process A Process B Process A and B are sharing X at the same time. In this case,
output will not be correct. For ex:
X=10, after executing A , value of X should be 10+10=20. Process
Read X Read X B will read X as 20 and after increment the value of X should be
20+10=30.

X=X+10 X=X+10

But, in this case both process are executing at the same time.
X=10 Process A So, if Process A is executing so it will read X as 10 but if process
B starts at this time so it will also read X as 10. Now again
X=10 Process B process A execute and read X as 10 and increment it by 10. so
now X=20, Now process B executes and read X as 10 and again
increment it by 10. So, again X=20, which is wrong.
X=20 Process A This is example of race condition. It happens because
of thread interference or thread interleaving.
X=20 Process B
ASET

public void run()


public class Main {
{ obj.increment();
int x=10;
}
public void increment()
});
{
x=x+10; Thread t2=new Thread(new Runnable()
} {
public static void main (String[] args) public void run()
{
{ obj.increment();
Main obj=new Main();
Thread t1=new Thread(new Runnable() }
{ });

t1.start();
t2.start();
System.out.println(obj.x);
}} O/P: Inconsistent
results
ASET
Memory Inconsistency Error

• Memory inconsistency errors occur when different threads have inconsistent


views of the same data.

• Changes done by one thread is not visible to another thread.


Balance=5000
Transaction A Transaction B
Read Balance
Balance=Balance-1000 Read Balance
Update balance Balance=Balance-1000
Update balance

In this case updates done by thread A in balance is not visible to thread B, So updated balance is 4000,
which is wrong. It should be 3000. It is called memory inconsistency error. It happens in case of parallel
execution. To avoid this, transaction B should not access balance when transaction A is executing.
ASET

Solution
Read X and X=X+10, should run in batch(one after another). It is called critical section.
X=10 is locked in this critical section. No another
process can read or modify X. Now next
Read X statement of this critical section will execute and
X=10 Process A x will become 20. Now all statements of critical
section has been executed, so, lock on A has been
Proces released.
X=20
sA
X=X+10

Process B
Now, Process B will read X=20 and it will lock X X=20 Process B
for its critical section, Now second statement of
Read X this critical section will execute and X=20+10=30. Proces
X=30
After this lock on X will be released. sB

https://www.youtube.com/watch?v=RH7G-N2pa8M&t=21s
X=X+10
Thread Synchronization
ASET

• There are two types of thread


synchronization mutual exclusive and inter-
thread communication.

• Mutual Exclusive
– Synchronized method.
– Synchronized block.
• Cooperation (Inter-thread communication in
java)
Synchronization ASET

Synchronization is built around an internal entity


known as the lock or monitor. Every object has a
lock associated with it.
By convention, a thread that needs consistent
access to an object's fields has to acquire the
object's lock before accessing them, and then
release the lock when it's done with them.
Java Synchronized Method
ASET

• 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.
Synchronized Block in Java
ASET

• Synchronized block can be used to perform


synchronization on any specific resource of the
method.
• Suppose we have 100 lines of code in our
method, but we want to synchronize only 5
lines, in such cases, we can use synchronized
block.
• If we put all the codes of the method in the
synchronized block, it will work same as the
synchronized method.
Synchronized Block in Java
ASET

• Synchronized block is used to lock an object for


any shared resource.
• Scope of synchronized block is smaller than the
method.
• A Java synchronized block doesn't allow more
than one JVM, to provide access control to a
shared resource.
• The system performance may degrade because
of the slower working of synchronized keyword.
• Java synchronized block is more efficient than
Java synchronized method.
Syntax ASET

synchronized (object reference expression) {


//code block
}
ASET

public void run()


{
public class Main
obj.increment();
{
int x=10; }
public void increment() });
{
Thread t2=new Thread(new Runnable()
x=x+10;
{
} public void run()
public static void main (String[] args) {
throws Exception obj.increment();
{
Main obj=new Main(); }
});
Thread t1=new Thread(new Runnable()
{ t1.start();
t2.start(); t1.join(); t2.join();
System.out.println(obj.x);
}} O/P: 30
ASET
Process Synchronization
class counter {
{ public void run()
int count; {
for(int i=1;i<=1000;i++)
public void increment() {
{ obj.increment();
count++; }
} }
});
}
public class Main Thread t2=new Thread(new Runnable()
{ {
public static void main(String[] args)throws Exception public void run()
{ {
for(int i=1;i<=1000;i++)
counter obj=new counter();
{
Thread t1=new Thread(new Runnable() obj.increment();
}
}
});
ASET

t1.start();
t2.start();
t1.join();
t2.join();
System.out.println(obj.count);
Will give you inconsistent results as threads are
} running at the same time. To solve this problem
} synchronized keyword should be used with the
name of function.

public synchronized void increment( )


{
count++;
}
Deadlock in Java
ASET

Deadlock in Java is a part of multithreading.


Deadlock can occur in a situation when a thread is
waiting for an object lock, that is acquired by another
thread and second thread is waiting for an object lock
that is acquired by first thread.
Since, both threads are waiting for each other to release
the lock, the condition is called deadlock.
Inter-thread Communication in Java
ASET

• Inter-thread communication or Co-operation is all


about allowing synchronized threads to communicate
with each other.
• Cooperation (Inter-thread communication) is a
mechanism in which a thread is paused running in its
critical section and another thread is allowed to enter
(or lock) in the same critical section to be executed. It
is implemented by following methods of Object class:
• wait()
• notify()
• notifyAll()
public class TestDeadlockExample1 {
public static void main(String[] args) {
ASET
final String resource1 = "ABC";
final String resource2 = "XYX";

// t1 tries to lock resource1 then resource2 Thread t2 = new Thread() {


Thread t1 = new Thread() {
public void run() {
public void run() { synchronized (resource2) {
synchronized (resource1) {
System.out.println("Thread 2: locked resource 2
System.out.println("Thread 1: locked ");
resource 1"); try { Thread.sleep(100);}
try { Thread.sleep(100);} catch (Exception e) {}
catch (Exception e) {} synchronized (resource1) {
synchronized (resource2) { System.out.println("Thread 2:
System.out.println("Thread 1: locke locked resource 1");
d } } }
resource e 2");
};
} } } };

t1.start(); t2.start(); }
50
// Inter-thread Communication in Java
ASET

synchronized void deposit(int


class Customer{
amount){ System.out.println("going to
int amount=10000; deposit...");
synchronized void withdraw(int amount){ this.amount+=amount;
System.out.println("going to withdraw..."); System.out.println("deposit
completed... "); notify(); } }
if(this.amount<amount){
System.out.println("Less balance; waiting for
public class Test{
deposit..."); public static void main(String args[]){
try{wait(); final Customer c=new Customer();
}catch(Exception e){} new Thread(){
} public void run(){c.withdraw(15000);}
this.amount-=amount;
}.start(); new Thread(){
System.out.println("withdraw completed...");
public void run(){c.deposit(10000);}
}.start(); }}
} 51

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy