Professional Documents
Culture Documents
JAVA
THREADING
THREADING
Introduction
INTRODUCTION
○ A program is an executable file containing a series of instructions
● Example: notepad++.exe
Having multiple processes without using threads Having multi-threaded processes consumes fewer
consumes more resources resources
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
7
THREADING
8 Creating Threads
CREATING THREADS
In Java, there are 2 methods to create threads:
9
EXTENDING THE THREAD CLASS
public class MyThread extends Thread {
public void run () {
// instructions that define
// the behavior of the 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
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
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
18
METHODS OF A THREAD
○ void join()
○ Given a thread named thread1
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");
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
26
CONCURRENT ACCESS
Priorities
○ 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”
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
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 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 Producer(CubbyHole c) {
this.cubbyhole = c;
}
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;
}
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?