23
Threading and Concurrency COM379T John Murray – [email protected]

Threading and Concurrency COM379T John Murray – [email protected]

Embed Size (px)

Citation preview

Page 1: Threading and Concurrency COM379T John Murray – john.murray@sunderland.ac.uk

Threading and Concurrency

COM379TJohn Murray – [email protected]

Page 2: Threading and Concurrency COM379T John Murray – john.murray@sunderland.ac.uk

The opposite of concurrency

The following is a diagrammatic view of a ‘sequential’ program

The flow of control is linear, i.e. from one instruction to the next.

Page 3: Threading and Concurrency COM379T John Murray – john.murray@sunderland.ac.uk

Concurrency

Concurrency consists of using multiple threads running at the same time.

Page 4: Threading and Concurrency COM379T John Murray – john.murray@sunderland.ac.uk

Forks

When a single thread spawns another thread it is referred to as a fork.

Page 5: Threading and Concurrency COM379T John Murray – john.murray@sunderland.ac.uk

Join

When other threads return their control back to the parent / master thread, this is known as a Join

Page 6: Threading and Concurrency COM379T John Murray – john.murray@sunderland.ac.uk

The Thread Class

In order to be able to implement threads in Java you need to make use of the Thread class.

Therefore your class must extend Thread

public class TryThread extends Thread

Page 7: Threading and Concurrency COM379T John Murray – john.murray@sunderland.ac.uk

The Thread Class

This class provides all the methods required to run your programs threads.

Methods include: start() – Create / Initiate the thread stop() – Stop execution of the thread sleep() – Pause the thread for x time join() – Dispose of the thread in correct

manor + many more, see the Thread API

Page 8: Threading and Concurrency COM379T John Murray – john.murray@sunderland.ac.uk

run() ing a Thread

Within your class you need to create a method called run(), this is where the thread execution will start

Contains any code you wish your thread to execute.

Can call other methods from your class here.

Page 9: Threading and Concurrency COM379T John Murray – john.murray@sunderland.ac.uk

Example – Creating two Threads

public class TryThread extends Thread {private String threadName;public TryThread(String theName) { // Constructor accepting a String

this.threadName = theName; // Assign string to Class attribute threadName}public static void main(String [] args) {

Thread first = new TryThread(“First”); // Define first threadThread second = new TryThread(“Second”); // Define Second threadfirst.start(); // Start first threadsecond.start(); // Start second threadtry {

System.in.read(); // Wait for enterfirst.stop(); // Stop first threadsecond.stop(); // Stop second thread

}catch (IOException e) {

System.out.println(e) }

}public void run() {

while(true) {System.out.println(“Name of thread: “ + threadName);

}}

}

Page 10: Threading and Concurrency COM379T John Murray – john.murray@sunderland.ac.uk

Synchronization

At some point in your program several threads may wish to access a single resource.

Synchronization ensures that only one thread at any given time can access the resource.

This is known as mutual exclusion

Page 11: Threading and Concurrency COM379T John Murray – john.murray@sunderland.ac.uk

Synchronized Methods

To make a method mutually exclusive you use the keyword synchronized

synchronized public void method1(){ // Code for method}

Only one of the synchronized methods in a class object can be executed by ANY thread at a time

Page 12: Threading and Concurrency COM379T John Murray – john.murray@sunderland.ac.uk

Lets take a closer look

Page 13: Threading and Concurrency COM379T John Murray – john.murray@sunderland.ac.uk

Thread Priorities

Threads have built-in priority scheduling.

If you wish a thread to have higher priority than others you can call the setPriority() method.

Priority’s: Low – 1 Default – 5 Highest - 10

Page 14: Threading and Concurrency COM379T John Murray – john.murray@sunderland.ac.uk

Thread Priorities

The priority of a thread is the same as that which created it.

setPriority() accepts a type of int IllegalArgumentException is thrown

if a priority < MIX_PRIORITY or > MAX_PRIORITY is set.

To find the current priority use getPriority()

int currentPriority = thread1.getPriority(); // Retrieve current prioritythread1.setPriority(7); // Set new Priority

Page 15: Threading and Concurrency COM379T John Murray – john.murray@sunderland.ac.uk

Fairness of execution

If all threads have the same priority then the current thread of execution may not relinquish is control of resources, i.e. the CPU

This leads to other threads experiencing what is known as ‘starvation’.

We therefore have to make the thread relinquish it’s control of the CPU

Page 16: Threading and Concurrency COM379T John Murray – john.murray@sunderland.ac.uk

Thread.sleep()

If you need to get a thread to free up the CPU so that other waiting threads can use it the sleep() method is called.

sleep() halts the current running of the thread and makes it release it’s access to the CPU for a set time.

Thread.sleep(timeInMilliseconds)

Page 17: Threading and Concurrency COM379T John Murray – john.murray@sunderland.ac.uk

Runnable Interface

So far to use threads we have used extends Thread.

This could cause problems if we also need to extend JFrame for GUI’s

Therefore we can implements Runnable

The runnable interface only declares one method run()

Page 18: Threading and Concurrency COM379T John Murray – john.murray@sunderland.ac.uk

Runnable examplepublic class RunnableTest implements Runnable{

Thread myThread; // Reference to our Thread

public RunnableTest(){

myThread = new Thread(this); // Create the threadmyThread.start(); // Start execution of the thread

}public static void main(String [] args){

RunnableTest myTest = new RunnableTest();

}public void run(){

// Execute some code}

}

Page 19: Threading and Concurrency COM379T John Murray – john.murray@sunderland.ac.uk

Considerations

When using threads several considerations have to be considered due to the nature of threading.

Starvation – Other lower priority threads not gaining access to CPU

Deadlock – Threads holding on to resources waiting for others <- Serious problem

Page 20: Threading and Concurrency COM379T John Murray – john.murray@sunderland.ac.uk

Starvation

Related to priorities Must ensure all threads will at some

point get CPU time. Keep checks on threads if not

executed in x time increase priority?

Page 21: Threading and Concurrency COM379T John Murray – john.murray@sunderland.ac.uk

Deadlock

Deadlock is a big issue in threaded systems.

It occurs when two threads are each waiting for the other thread to release control of a resource so that they can use it to complete.

Page 22: Threading and Concurrency COM379T John Murray – john.murray@sunderland.ac.uk

Deadlock

Page 23: Threading and Concurrency COM379T John Murray – john.murray@sunderland.ac.uk

Deadlock

P1 has control of R1 but needs R2 P2 has control of R2 but needs R1 Neither P1 or P2 will release their

resource. Therefore one of the threads needs

to yield() its control of the resource