You are on page 1of 44

OBJECT ORIENTED PROGRAMMING - 2

JAVA
THREADING
THREADING
Introduction
INTRODUCTION
○ A program is an executable file containing a series of instructions
● Example: notepad++.exe

○ A process is an active instance of a program


● Thus the program becomes running in memory
● A program running multiple times has multiple "processes" created
● Example: running the program above several times

○ A thread is the smallest executable unit of a process (part of a process).


● Example: when notepad++.exe is started, the operating system will execute the
main process thread 4
INTRODUCTION
Process Thread

Heavy consumer of resources Light-weight resource consumer

Having multiple processes without using threads Having multi-threaded processes consumes fewer
consumes more resources resources

One thread can read, write, change data of another


A process is independent of others
thread

Each process runs the same code but has its own
Threads share the memory location of their process
memory location

5
INTRODUCTION
○ In Java, it is possible to simulate the execution of
several tasks in the same program at the same
time.
● “Multi-threading”
● The execution of each task is called a “thread”

○ A thread
● is a series of instructions to execute
● is not an object

○ A Java program ends when the execution of all


threads is complete
6
INTRODUCTION
Benefits of using Threads
○ To maintain responsiveness of an application during a long running task

○ To enable cancellation of separable tasks

○ To enable concurrency within a process

○ To allow utilization of multiprocessor architectures


● greater scale and efficiency

7
THREADING
8 Creating Threads
CREATING THREADS
In Java, there are 2 methods to create threads:

○ Implement the Runnable interface

○ Extend the Thread class


● more advanced than the Runnable interface
● a maximum of "threading" features

9
EXTENDING THE THREAD CLASS
public class MyThread extends Thread {
public void run () {
// instructions that define
// the behavior of the thread
}
}

public static void main (String [] args) {


MyThread t1 = new MyThread ();
t1.start();
}

A thread lives until the end of its run () method 10


IMPLEMENTING THE RUNNABLE INTERFACE
public class Task implements Runnable {
public void run () {
// instructions that define
// the behavior of the thread
}
}

public static void main ( String [] args ) {

Task job = new Task (); //Runnable job=new Task();

Thread t1 = new Thread (job);


t1.start ();
}
11
THREADING
12 Methods of a Thread
METHODS OF A THREAD

○ void run()
● Contains the instructions to be executed by the thread
● May be called several times
● Does not support multi-threading

○ void start()
● Starts the thread execution
● JVM will call the run () method of the thread
○ called only once
● Supports multi-threading
13
METHODS OF A THREAD

○ static void sleep(long m)


● Temporarily stops the execution of the current thread for m milliseconds

○ static void sleep(long m, long n)


● Temporarily stops the execution of the current thread for m milliseconds,
and n nanoseconds

14
METHODS OF A THREAD

○ void interrupt()
● When the thread is executing the sleep(), wait(), and join() methods, those methods will
throw an InterruptedException.

● Otherwise, a flag is set that the thread can examine to determine that
the interrupt() method has been called.

○ boolean isInterrupted()
● Returns a boolean that indicates whether the specified thread has been interrupted. This
method simply returns a flag that is set by the interrupt() method.

15
METHODS OF A THREAD

○ static void yield()


● Performs a temporary stop of the current thread by "passing its turn"
● Allows other threads having the same priority or higher priority in the queue to be
executed (those with lower priority will not execute)
○ this differentiates the yield() method from the sleep() method
○ If no other threads exist in the queue OR only threads having a lower priority exist then
the stopped thread will be resumed by the JVM scheduler
○ If only threads of the same priority exist, the choice of one of them depends on the
Platform

16
METHODS OF A THREAD - EXAMPLE
public class YieldThread extends Thread {
public void run() {
for ( int count = 0; count < 4; count++) {
System.out.println( count + "From: " + getName() );
yield();
End
}
0From: Thread-
} 0
} 0From: Thread-
1
public class TestYield { 1From: Thread-
0
public static void main( String[] args ) {
1From: Thread-
YieldThread first = new YieldThread(); 1
YieldThread second = new YieldThread(); 2From: Thread-
first.start(); 0
second.start(); 2From: Thread-
17
1
System.out.println( "End" );
3From: Thread-
} 0
METHODS OF A THREAD

○ String getName()
○ Returns the name of the thread

○ void setName(String name)


○ Modifies the name of the thread

18
METHODS OF A THREAD

○ void join()
○ Given a thread named thread1

○ thread1.join(); will allow the


thread that is running (i.e. main) to
stop temporarily until the thread
completes its execution

19
Output
1
2
METHODS OF A THREAD 3
4
○ void join() 5
1
1
class TestJoinMethod extends Thread{ public static void main(String args[]){ 2
public void run(){ TestJoinMethod t1=new TestJoinMethod(); 2
for(int i=1;i<=5;i++){ TestJoinMethod t2=new TestJoinMethod(); 3
try{ TestJoinMethod t3=new TestJoinMethod(); 3
Thread.sleep(500); t1.start(); 4
} 4
catch(Exception e){ try{ 5
System.out.println(e); t1.join(); 5
} }
System.out.println(i); catch(Exception e){
} System.out.println(e);
} }
}
t2.start(); 20
t3.start();
}
THREADING
21 Lifecycle of a Thread
LIFECYCLE OF A THREAD

22
WHAT WILL BE THE OUTCOME(S) OF THE BELOW PROGRAM?
public class MyTask implements Runnable {
public void run () {
for ( int i = 0; i < 30; i++) {
String name = Thread.currentThread().getName ();
System.out.println (name + "is executing");
}
}
public static void main ( String [] args ) {
Runnable task = new MyTask ();
Thread a = new Thread (task);
a.setName ("Caroline");

Thread b = new Thread (task);


b.setName ("Cedric");
System.out.println("1");
a.start();
System.out.println("2");
b.start();
23
System.out.println("3");
}
}
A POSSIBLE OUTCOME OF THE EXECUTION
1 Cedric is executing
2 Caroline is executing
3 Caroline is executing
Cedric is executing Caroline is executing
Caroline is executing Caroline is executing
Caroline is executing Caroline is executing
Caroline is executing Caroline is executing
Caroline is executing Cedric is executing
Caroline is executing Cedric is executing
Caroline is executing Cedric is executing
Caroline is executing Cedric is executing
Caroline is executing … 24

Cedric is executing
THREADING
25 Concurrent Access
CONCURRENT ACCESS
Priorities
○ Every thread has a priority

○ When a thread is created, it inherits the priority of the thread that created it

○ The priority values range from 1 to 10, in increasing priority

○ The thread with he highest priority is scheduled to run by the JVM.


● In case two threads have the same priority a FIFO ordering is followed.

26
CONCURRENT ACCESS
Priorities

○ Threads have a priority value:


○ Thread.MIN_PRIORITY (1)
○ Thread.NORM_PRIORITY (5) //default priority of the main thread
○ Thread.MAX_PRIORITY (10)

○ Useful Methods:
○ int getPriority() ;
○ void setPriority(int p) ;

○ However: “Avoid the temptation to use thread priorities, since they increase platform
27
dependence and can cause liveness problems. Most concurrent applications can use the
default priority for all threads.”
CONCURRENT ACCESS
○ Threads share the same resources
● Memory
● Attributes of the same shared object
● Methods of the same shared object
● Etc.

○ In some situations, it is necessary to block concurrent access to the same attribute or method
● Case where 2 threads are using the same object

○ Examples
● Bank Transactions
● Reservations flight tickets 28
CONCURRENT ACCESS
○ Protection of some sections is required to avoid “deadlocks”

○ A solution to resolve the concurrent access issues:

synchronized public void myMethod {

// This method may not be executed concurrently...

○ Synchronized methods define a « critical section »


29
SYNCHRONIZATION
○ Each object has a “monitor” that is a token used to determine which
application thread has control of a particular object instance

○ In execution of a synchronized method, access to the object monitor must be


gained before the execution
● Access to the object monitor is queued
● If a thread A tries to acquire ownership of a monitor and a different thread has already entered
the monitor, the current thread (A) must wait until the other thread leaves the monitor

○ Beware of synchronizing static methods!


● Marking a static method a synchronized associates a monitor with the class itself.
30
THE FOLLOWING BLOCS ARE EQUIVALENT
public synchronized void a() {
//… some code …

public void a() {

synchronized (this) {
//… some code …
}
}
31
SYNCHRONIZATION
public class MyTask implements Runnable {
public void run () {
synchronized (this){
for ( int i = 0; i < 30; i++) {
String name = Thread.currentThread().getName();
System.out.println (name + " is executing");
}
}
}
32
RESULTS

Caroline is executing
Caroline is executing
Caroline is executing
Caroline is executing
Caroline is executing
Caroline is executing
Cedric is executing
Cedric is executing
Cedric is executing
Cedric is executing
Cedric is executing
Cedric is executing
Cedric is executing 33


THREADING
34 wait() and notify() Methods
WAIT() AND NOTIFY() METHODS
wait()
○ Executes in a synchronized block

○ Effect:
● Releases the lock (monitor)
● Puts the thread on hold (blocked)
○ until another thread executes the notify () or notifyAll () method

○ Similarity to yield() method:


● yield() places a thread in the queue
● wait() blocks it and waits for notify() to return the thread to the queue
35
○ the scheduler chooses it, and the thread tries to acquire the monitor to lock the object /
function.
WAIT() AND NOTIFY() METHODS
notify()
○ Awakens one of the threads that are waiting for the monitor
● threads that are in the wait state

notifyAll()
○ Awakens all of the threads that are waiting for the monitor

36
WAIT() AND NOTIFY() METHODS
public class CubbyHole {
private int contents;
public synchronized void put(int value) {
private boolean available = false;
if (available == true) { //something is available, wait!
try {
public synchronized void get() {
//wait for Consumer to get value
if (available == false) { //nothing available, wait! wait();
try { } catch (InterruptedException e) { }
//wait for Producer to put value }
contents = value;
wait(); available = true;
} System.out.println(“produce " + contents);
catch (InterruptedException e) { } notifyAll();
}
} }
available = false;
System.out.println(“consume " + contents);
notifyAll();
}
37
THREADING
38 Application
APPLICATION 1
○ Complete the CubbyHole class by adding a Producer thread and a Consumer thread.

○ The producer shall use the put method to produce an item

○ The consumer shall use the get method to consume an item created by the producer

39
APPLICATION 1
public class CubbyHole {
private int contents;
private boolean available = false;

public synchronized int get() {


if (available == false) { //nothing available, wait!
try {
public synchronized void put(int value) {
wait();
} if (available == true) { //something is available, wait!
catch (InterruptedException e) { } try {
wait();
}
} catch (InterruptedException e) { }
available = false; }
System.out.println("Consumer: " + contents); contents = value;
notifyAll(); available = true;
System.out.println("Producer: " + contents);
return contents;
} notifyAll();
} 40
}
APPLICATION 1
public class Producer extends Thread {
private CubbyHole cubbyhole;

public Producer(CubbyHole c) {
this.cubbyhole = c;
}

public void run() {


for(int i=0;i<10; i++){
cubbyhole.put(i);

try {
sleep((int)(Math.random() * 100));
}
catch (InterruptedException e) {
}
}
41
}
}
APPLICATION 1
public class Consumer extends Thread {
private CubbyHole cubbyhole;

public Consumer(CubbyHole c) {
this.cubbyhole = c;
}

public void run() {


int value = 0;

for(int i=0;i<10;i++){
value = cubbyhole.get();
}
}
}
42
APPLICATION 1
public static void main (String[] args) throws InterruptedException { Output
Producer: 0
CubbyHole c = new CubbyHole();
Consumer: 0
Producer p1 = new Producer(c); Producer: 1
Consumer c1 = new Consumer(c); Consumer: 1
Producer: 2
p1.start();
Consumer: 2
c1.start(); Producer: 3
} Consumer: 3
Producer: 4
Consumer: 4
Producer: 5
Consumer: 5
Producer: 6
Consumer: 6
Producer: 7
Consumer: 7
Producer: 8
Consumer: 8
Producer: 9
Consumer: 9 43
THANK YOU!
44 Questions?

You might also like