Concurrent Programming
Mathematical Example
Consider finding a single root using the quadratic formula:
\[x=\frac{-b+\sqrt{b^2-4ac}}{2a}\]This can be split into several operations.
Concurrent Operations
These operations don’t rely on any other part of the expression.
- $t_1=-b$
- $t_2=b\times b$
- $t_3=4\times a$
- $t_4=2\times a$
Serial Operations
These parts have prerequisites.
- $t_5=t_3\times c$
- $t_5=t_2-t_5$
- $t_5=\sqrt{t_5}$
- $t_5=t_1+t_5$
- $x=\frac{t_5}{t_4}$
Java Threads
When a Java program starts up, a single thread is always created for the program
JVM also has own threads for garbage collection, screen updates, event handling…
- New threads may be created by the programmer by extending the Thread class.
- Threads may be managed directly by kernel, or implemented at user level by a library.
- Former is less efficient.
- In latter, if one thread blocks, all threads will block.
Java Thread Class
public class Thread extends Object implements Runnable
- A
Thread
implements arun()
method that defines what processing will be carried out during theThread
’s lifetime. - Threads may be started within
main()
and run simultaneously, sharing variables, etc.
Example
class Worker1 extends Thread {
public void run() {
System.out.println(“I am a worker thread”);
}
}
public class First {
public static void main (String args[]) {
Worker1 runner = new Worker1();
runner.start();
System.out.println(“I am the main thread”);
}
}
This doesn’t have a definite order. Worker1
or main
may get run first.
Method
The class Worker1
is derived from the Thread
class and the work of the new thread is specified in the run()
method.
- In
main()
we create a newWorker1
object. - Calling the
start()
method:- Allocates memory and initialises the new thread.
- Causes the
run()
method to be called.
- Original thread and new thread now run in parallel.
Java Thread States
graph LR
a[ ] -->|new| New
New -->|"start()"| Runnable
Runnable -->|"I/O, sleep()..."| Blocked
Blocked --> Runnable
Runnable -->|termination| Dead
All threads capable of execution are in the runnable state.
This includes the currently executing thread.