0% found this document useful (0 votes)
14 views46 pages

4-COE312 - Lecture Java Threads

The document discusses Java threads and multitasking, explaining the differences between multiprocessing and multithreading. It outlines the states of a thread, methods for creating threads, and key functions such as start() and run(). Additionally, it addresses thread synchronization and provides examples of implementing threads in Java.

Uploaded by

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

4-COE312 - Lecture Java Threads

The document discusses Java threads and multitasking, explaining the differences between multiprocessing and multithreading. It outlines the states of a thread, methods for creating threads, and key functions such as start() and run(). Additionally, it addresses thread synchronization and provides examples of implementing threads in Java.

Uploaded by

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

1

Java Threads
COE312
Omar Arif
2

 Modern operating systems are able to run more


than one process at the same time, even if there is
only one CPU present on the computer.
 This is possible because most computer programs
Multitasking: exhibit "dead time" during execution.
doing things  These intervals occur when programs encounter
periods of inactivity
in parallel  Graphical User Interface (GUI) programs, for
example, experience lulls during user interactions
 Programs accessing databases may encounter
delays
3

 Multitasking can be achieved by two ways:


Process-based Multitasking(Multiprocessing)
Thread-based
Multitasking(Multithreading)

Multitasking:
doing things
in parallel
4

Multiprocessing Multithreading
Each process have its
own address in
Threads share the
memory i.e. each
same address space.
process allocates
separate memory area.

Multitasking
5

Multiprocessing Multithreading
Each process have its
own address in
Threads share the
memory i.e. each
same address space.
process allocates
separate memory area.
Process is
Thread is lightweight.
heavyweight.
Multitasking
6

Multiprocessing Multithreading
Each process have its
own address in
Threads share the
memory i.e. each
same address space.
process allocates
separate memory area.
Process is
Thread is lightweight.
heavyweight.
Multitasking Cost of communication Cost of communication
between the process is between the thread is
high. low.
7

Multiprocessing Multithreading
Each process have its
own address in
Threads share the
memory i.e. each
same address space.
process allocates
separate memory area.
Process is
Thread is lightweight.
heavyweight.
Multitasking Cost of communication Cost of communication
between the process is between the thread is
high. low.
Context-switching
require some time for Context-switching
saving & loading between the threads
registers, memory takes less time than
maps, updating lists process.
etc.
8

 Multithreading is one way to do many things in


parallel (at the same time) in your Java program.
 https://www.javatpoint.com/multithreading-in-java

Multithreadi
ng
9
• Thread is an execution unit.
• Your java program running inside a JVM
can have several threads at the same
time.

Your Java
Program
What is a
Java
Program
thread?

JVM

Computer
10

 The java thread states are as follows:


1.New - The thread is in new state if you create an
instance of Thread class but before the invocation
of start() method.
2.Runnable - The thread is in runnable state after
invocation of start() method, but the thread
scheduler has not selected it to be the running
States of thread.

thread 3.Running - The thread is in running state if the


thread scheduler has selected it.
4.Non-Runnable (Blocked) - This is the state
when the thread is still alive, but is currently not
eligible to run.
5.Terminated - A thread is in terminated or dead
state when its run() method exits.
11

States of a Thread
12

<<interfacce>>
Thread
Runnable
Implements
+start() public void run();

 There are two ways to create a thread:


Creating 1.By extending Thread class
thread 2.By implementing Runnable interface.
13

<<interfacce>>
Thread
Runnable
Implements
+start() public void run();

 There are two ways to create a thread:


1.By extending Thread class
Creating
thread
14

<<interfacce>>
Thread
Runnable
Implements
+start() public void run();

 There are two ways to create a thread:


2. By implementing Runnable interface.
Creating
thread
15
 run()
 This method gets called when thread is
running
 Describes a thread’s behavior.
 Should never be called directly.

 start()
 Allocates resources for a thread like
Key activation record stack.

functions of  Calls run() function to start the thread


running.
a Thread  sleep()
 Puts the thread in hibernation until it is
awoken.
 Gives other threads a chance to get their
work done.
 Throws InterruptedException
16

Problem  Create multiple threads to print random numbers.


Solution Note: main also has a
17
thread associated with it.
So three threads are
public class Main {
public static void main(String[] args) { running when you run this
// create two threads to generate random numbers program 1) main, 2) t1, 3)
ThreadDemo t1 = new ThreadDemo("Thread 1"); t2.
ThreadDemo t2 = new ThreadDemo("Thread 2");
}
}

Output:
These two instances of
Creating Thread 1
thread will run in parallel
Creating Thread 2
in addition to main.
Running Thread 1
Running Thread 2
Thread 1: 20
Thread 2: 17
Thread 1: 43
Thread 2: 90
Thread 2: 79
Both threads t1 and t2 run in parallel Thread 1: 77
to generate their own random
numbers.
Thread 2: 19
Thread 1: 1
Thread Thread 2 exiting.
Thread Thread 1 exiting.
import java.util.Random; 18

//Thread Example by extending Thread class


public class ExtendThread extends Thread{
Random r = new Random();

public ExtendThread(String name){ Constructor starts the thread by calling


super(name); the start function. start function will do
System.out.println("Creating " + this.getName() ); some housekeeping and then call the
this.start(); run() function.
}

public void run() { Behavior of the thread is defined in


System.out.println("Running " + this.getName() ); the run() function.
try {
for(int i = 4; i > 0; i--) { sleep lets the thread rest for 1
System.out.println(this.getName() + ": " + r.nextInt(0,100));second.
// Let the thread sleep for a while.
Thread.sleep(150);
}
}catch (InterruptedException e) {
System.out.println("Thread " + this.getName() + " interrupted.");
}
System.out.println("Thread " + this.getName() + " exiting.");
}
}

Warning: DO NOT CALL the


run() function directly.
19

 When we create a thread by extending the


Thread class, then we can’t extend any other
class because Java does not support multiple
inheritance
Issue  Creating a thread by implementing Runnable
interface is more flexible as it uses composition
and not inheritance. Therefore, it should be
preferred over the first method.
import java.util.Random;

public class ImplementInterface implements Runnable{ 20


Random r = new Random();
private Thread t;

ImplementInterface(String name){ • Must create an instance of a


t = new Thread(this); Thread.
t.setName(name);
System.out.println("Creating " + t.getName() ); • Attach onself to this thread
t.start(); and start oneself.
}

public void run() {


System.out.println(t.getName());

System.out.println("Running " + t.getName());


try {
for(int i = 4; i > 0; i--) {
System.out.println(t.getName() + ": " + No change required
r.nextInt(0,100));
// Let the thread sleep for a while. here.
Thread.sleep(150);
}
}catch (InterruptedException e) {
System.out.println("Thread " + t.getName() +
" interrupted.");
}
System.out.println("Thread " + t.getName() + "
exiting.")
}
}
21

 Approach 1 (not recommended)


1. Derive your class from the Thread class
2. Implement the run function.
3. In your constructor do:
Two ways to 1. this.start()

create a  Approach 2 (recommended)


1. Implement the Runnable interface
Thread 2. Implement the run function
3. In your constructor do:
1. Thread t = new Thread(this)
2. t.start()
22

 What will this class do?

public class Print implements Runnable {


int n;

Print(int n){
this.n = n;

Another Thread t = new Thread(this);


t.start();

Example }

public void run() {


for(int i =1; i<=n; i++)
System.out.println("from:"+this+" print "+i);
}
}
23

What will the program do and what is bothersome?

public class Main {

public static void main(String[] args) {

Print n1 = new Print(10);

Example Print n2 = new Print(15);

System.out.println("Hasta Lavista Baby!");

}}
24

 The thread main in the parent program (Main) that


created the two threads n1 and n2 will finish running BUT
the two print threads will still be running because they
are independent.
 This is not a good thing. We want Main to wait until all the
threads it created have finished running.

Problem
with the Main has finished running Hasta Lavista Baby!
from:print@92bcdac print 1

Example
from:print@4c329cd1 print 1
from:print@92bcdac print 2
from:print@4c329cd1 print 2
n1 and n2 are still running from:print@92bcdac print 3
from:print@4c329cd1 print 3
from:print@92bcdac print 4
from:print@4c329cd1 print 4
25

T.join -> wait until T dies or finishes running.

public class Main {

How to wait public static void main(String[] args) throws


InterruptedException {
for someone Print n1 = new Print(10);

to die? Print n2 = new Print(15);

// wait for n1 and n2 to die or finish running.


n1.getThread().join();
n2.getThread().join();

System.out.println("Hasta Lavista Baby!");

}}

Need to implement function called getThread.


26

• We need to remember our


public class Print implements Runnable { thread and create a function
int n; called getThread that returns
private Thread t; a pointer to our thread.
Print(int n){
• We need this because join
this.n = n; needs the pointer to our
t = new Thread(this); thread.
t.start();
}

from:print@3edac053 print 7
public Thread getThread() {
from:print@54f50172 print 9
return t; from:print@3edac053 print 8
} from:print@3edac053 print 9
from:print@3edac053 print 10
from:print@54f50172 print 10
public void run() { from:print@3edac053 print 11
from:print@3edac053 print 12
for(int i =1; i<=n; i++)
from:print@3edac053 print 13
System.out.println("from:"+this+" print "+i); from:print@3edac053 print 14
} from:print@3edac053 print 15
Hasta Lavista Baby!
}

Prints at the end!


27

 Why not call the run() function directly from


Main?

Common
Question
28

Calling run directly:

• The thread t runs in the same runtime stack as the


main(){
calling function (main).
… • This means thread t will NOT run in parallel with
t.run()
main.
t.run() • The run() of the thread t will behave like any other
main function main calls.
Calling
Calling start:
start:

The thread t has its own runtime


main(){ stack and runs in parallel with main.

t.start()
start() creates a run-time stack
main t.run()
and calls the run() function in the
new run-time stack.
29

 The Thread class provides methods to


change and get the name of a thread.
 By default, each thread has a name i.e.
thread-0, thread-1 and so on. Use getName()
to get the name
 We can change the name of the thread by
Naming a using setName() method.
thread
public static Thread currentThread(): The currentThread()
method returns a reference of currently executing thread.

public void run(){


System.out.println(Thread.currentThread().getName());
}
30

 When two or more threads access or change a


shared object, this may lead to undesirable effects

The  Thread Synchronization is a process of allowing only one


thread to use the object when multiple threads are trying
Synchroniza to use the particular object at the same time

tion Problem  There are two methods of synchronization:


 internal (method)
 External (block)
31

 Lets say we have program that counts the


number of people entering a building from
muliple doors

Example
32

public class Counter {


private int count;
Counter(){
count = 0;
}
public int getCounter() {
return count;
}
public void addCounter() {
try {
int val = count;
Thread.sleep(10);
count = val+1;
System.out.println("Counter: "
+ count);

}catch(Exception e) {
}
}
}
33

public class Door implements Runnable{ Create a thread and start onself.
public Thread t;
Counter counter;

Door(Counter c){
counter = c;
t = new Thread(this);
Simulate 5 people entering the
t.start();
} door

public void run() {


for (int i=0; i<5; i++) {
counter.addCounter();
}
}
}
34

public class Main {

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


Counter counter = new Counter();

Door door1 = new Door(counter);


Door door2 = new Door(counter);

door1.t.join();
door2.t.join();

System.out.println("total: " + counter.getCounter());


}
}
Output:
Door@244b1f29 1
Door@6d7abb09 1
Door@244b1f29 2
Note that the Counter object Door@6d7abb09 4
counter is being shared by Door@244b1f29 4
the two door1 and door2 Door@244b1f29 5
Door@244b1f29 6
Door@6d7abb09 6
Door@6d7abb09 7
Door@6d7abb09 8
total: 8
35

 When two or more threads access or change a


shared object, this may lead to undesirable effects

The  Thread Synchronization is a process of allowing only one


thread to use the object when multiple threads are trying
Synchroniza to use the particular object at the same time

tion Problem  There are two methods of synchronization:


 Internal/Method synchronization
 External/Block synchronization
 If you declare any method as synchronized, it is 36

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.
Method public class Counter {

Synchonizati
private int count;
Counter(){
count = 0;

on }
public synchronized void addCounter() {
try {
int val = count;
Thread.sleep(10);
count = val+1;
System.out.println("Counter: " +
Integer.toString(count));
}catch(Exception e) {

}
}
}
37

 Synchronized block can be used to perform


synchronization on any specific resource of the
method.
Block  Suppose we have 50 lines of code in our method,

Synchroniza but we want to synchronize only 5 lines, in such


cases, we can use synchronized block.
tion  If we put all the codes of the method in the
synchronized block, it will work same as the
synchronized method.
38

public class Door implements Runnable{


public Thread t;
Counter counter; Only allow one thread
Door(Counter c){ to access b within the
counter = c;
synchronized block.
t = new Thread(this);
t.start();
}
public void run() {
for (int i=0; i<5; i++) {

Block synchronized(counter) {
Critical Section

Synchonizati counter.addCounter();

on
}
} Output:
}
}
Counter: 1
Counter: 2
Counter: 3
Counter: 4
Counter: 5
Counter: 6
Surround the code that Counter: 7
Counter: 8
accesses the shared object
Counter: 9
with the synchronized block. Counter: 10
total: 10
 Write a program that has two classes for female 39

and male students.


 There is only one pencil and one notebook.
 Each student must wait to acquire both the the
pencil and the notebook before they can write.
 Famale Students
1. Acquire the pen
2. Acquire the notebook
Problem 3. Write
 Male Students
1. Acquire the notebook
2. Acquire the pen
3. Write
40

public class {

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

Main String notebook = "shared notebook";


String pencil = "shared pencil";

Program new female_student(notebook, pencil);


new female_student(notebook, pencil);

}
}
41

public class female_student implements Runnable {


String notebook;
String pencil;
Thread t;

female_student(String notebook, String pencil) {

this.notebook = notebook;
this.pencil = pencil;
t = new Thread(this);

Female
t.start();
}

Students
public void run() {
while (true) {
// wait for the notebook to become available
synchronized (notebook) {

System.out.println(this + " has the notebook.");

// now wait for pencil to become available.


synchronized (pencil) {
System.out.println(this + " has the pencil.");
System.out.println(this + " has pencil and notebook so they can write");
}
}}}}
42

 The progam runs fine with multiple female


students.

female_student@28d01fb4 has pencil and notebook so they can write


female_student@28d01fb4 has the notebook.

Running
female_student@28d01fb4 has the pencil.
female_student@28d01fb4 has pencil and notebook so they can write
female_student@28d01fb4 has the notebook.

with female_student@28d01fb4 has the pencil.


female_student@28d01fb4 has pencil and notebook so they can write
female_student@226e0250 has the notebook.

multiple female_student@226e0250 has the pencil.


female_student@226e0250 has pencil and notebook so they can write
female_student@226e0250 has the notebook.

female female_student@226e0250 has the pencil.


female_student@226e0250 has pencil and notebook so they can write

students
female_student@226e0250 has the notebook.
female_student@226e0250 has the pencil.
female_student@226e0250 has pencil and notebook so they can write
female_student@226e0250 has the notebook.
female_student@226e0250 has the pencil.
43

 The program will hang!

public class Driver {

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


String notebook = "shared notebook";
String pencil = "shared pencil";

Program // female students


for (int i = 0; i<10; i++)

with Male new female_student(notebook, pencil);


// male students

and Female
for (int i = 0; i<10; i++)
new male_student(notebook, pencil);
}

Students
}

female_student@226e0250 has the notebook.


female_student@226e0250 has the pencil.
female_student@226e0250 has pencil and notebook so they can write
female_student@226e0250 has the notebook.
female_student@226e0250 has the pencil.
female_student@226e0250 has pencil and notebook so they can write
female_student@226e0250 has the notebook.
male_student@2ee6a5aa has the pencil.
44

female_student@226e0250 has the notebook.


female_student@226e0250 has the pencil.
female_student@226e0250 has pencil and notebook so they can write
female_student@226e0250 has the notebook.
female_student@226e0250 has the pencil.
female_student@226e0250 has pencil and notebook so they can write
female_student@226e0250 has the notebook.
male_student@2ee6a5aa has the pencil.

What
happened?  female_student@226e0250 has the notebook and is waiting for the
pencil.
 male_student@2ee6a5aa has the pencil and it waiting for the notebook.
 Both will wait for each other for ever and this is called a Deadlock.
45

 When two threads will wait to acquire resources


held by others and will wait for ever.
 Solutions:
1. Make all (female and male) acquire the resources in
the same order. For example, we did not have any
issues when there were multiple females because
they are all acquiring pencil and notebook in the

Deadlock
same order.
2. Don’t wait for ever but release a resource if not
availeble through timeout. This can be done in Java
using a more advanced concept called a Lock. We
will not cover this topic in our class but if you are
interested please see
(https://docs.oracle.com/javase/7/docs/api/java/util/
concurrent/locks/Lock.html)
46

 Threads allow us to do multiple things at the same


time.
 When threads access a shared object, then
we must use synchronization.

Summary

 run() must never be synchronized.


 We should ensure that we do not have deadlocks.

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