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

Preview:

Citation preview

Threading and Concurrency

COM379TJohn 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.

Concurrency

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

Forks

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

Join

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

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

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

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.

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);

}}

}

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

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

Lets take a closer look

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

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

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

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)

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()

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}

}

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

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?

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.

Deadlock

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

Recommended