程序代写代做代考 concurrency Java CO2017 — Week3L1 — Threads in Java
CO2017 — Week3L1 — Threads in Java
CO2017 — Week3L1 — Threads in Java
Dr Gilbert Laycock (gtl1)
2016–02–08
gtl1–R593 W3L1 — Java Threads 2016–02–08 1 / 17
Recap/overview
Recap and Lecture Overview
Recap
The nature of concurrent programming is multiple processes/threads
running in parallel
Processes may share resources
Solutions need to guarantee mutual exclusion, progress, bounded waiting
Overview of this lecture
How can Java support concurrent programming?
Java Thread class, and Runnable interface
Java ThreadGroup class, Executors and ThreadPools
Simple examples
gtl1–R593 W3L1 — Java Threads 2016–02–08 2 / 17
Concurrency in Java
Concurrency in Java
Java Virtual Machine (JVM) allows an application to have multiple
threads running concurrently
the thread concept is supported by
the classes java.lang.Thread and java.lang.ThreadGroup
the interface java.lang.Runnable
Two ways to create a new thread
Extending the Thread class
Implementing the Runnable interface
gtl1–R593 W3L1 — Java Threads 2016–02–08 3 / 17
Concurrency in Java
Two ways to create a thread
Extend Thread class
Implement Runnable class
MyRunnable
+run(): void
Thread
+run(): void
ExampleThread
+run(): void
Runnable
+run(): void
Thread
gtl1–R593 W3L1 — Java Threads 2016–02–08 4 / 17
Concurrency in Java Extend Thread class
Extending Java Thread Class
Declare a subclass of Thread, overriding its run() method
public class ExampleThread extends Thread {
int parameter;
ExampleThread(int para) { parameter = para; }
public void run() {
… // what the thread should do
}
}
Create an instance of the subclass and start executing it
ExampleThread t = new ExampleThread(10);
t.start();
gtl1–R593 W3L1 — Java Threads 2016–02–08 5 / 17
Concurrency in Java Implement Runnable interface
Implementing the Interface Runnable
Java does not permit multiple inheritance
So usually more convenient to implement run() from Java interface
Runnable instead of deriving from Thread
Runnable declares (just) the run() method
public interface Runnable {
public abstract void run();
}
We can extend other classes while implementing Runnable
In fact, the Thread class just implements Runnable
public class Thread
extends Object
implements Runnable
gtl1–R593 W3L1 — Java Threads 2016–02–08 6 / 17
Concurrency in Java Implement Runnable interface
Implementing the Interface Runnable (Cont’d)
First declare a class implementing Runnable
public class MyRunnable extends SomeClass
implements Runnable {
int parameter;
MyRunnable (int para) { parameter = para; }
public void run() {
… // what should the thread do?
}
}
Threads can then be allocated and started by
MyRunnable r = new MyRunnable(10);
Thread t = new Thread(r);
t.start();
gtl1–R593 W3L1 — Java Threads 2016–02–08 7 / 17
Concurrency in Java Thread methods
Methods of Thread Class
Some principal methods of the Thread class
t.start(): Causes thread t to begin execution; (JVM will call run()
concurrently)
t.run(): Call the run method of thread t directly (with no concurrency)
Thread.sleep(ms): Cease the execution of current thread for ms
milliseconds
t.join(): Causes the calling thread to wait (block) for the thread t to
finish
Refer to the Java documents about Thread class and Runnable
interface.
gtl1–R593 W3L1 — Java Threads 2016–02–08 8 / 17
Concurrency in Java Using threads
Outline code using Threads
public class T1 extends Thread {
// attributes and constructor
public void run() { /* thread functionality */ }
}
……
public class Tn extends Thread {
// attributes and constructor
public void run() { /* thread functionality */ }
}
public class MainProgram {
public static void main(String[] args) {
B;
T1 t1 = new T1(); …; Tn tn = new Tn();
t1.start(); …; tn.start();
I;
t1.join(); …; tn.join();
F; }
}
gtl1–R593 W3L1 — Java Threads 2016–02–08 9 / 17
Concurrency in Java Using threads
The Semantics of start()
The execution of B finishes before t1,. . . ,tn as they have not been
started yet;
The effect of t1.start(),. . . ,tn.start() is equivalent to interleaving
the atomic actions of the started threads;
Execution of statement I can interleave with t1,. . . ,tn
Execution of statement F does not begin until all of t1,. . . ,tn have
completed
Execution of main() terminates only if all of the started threads (and I
and F) terminate
If we replace t1.start(),. . . ,tn.start() with t1.run(),. . . ,tn.run(),
the program will become a sequential program
gtl1–R593 W3L1 — Java Threads 2016–02–08 10 / 17
Concurrency in Java Examples
Thread Example
class ExampleThread extends Thread {
int _id;
ExampleThread(int id) { _id = id; }
public void run() {
System.out.println(“This is thread: ” + _id);
}
public static void main(String[] args) {
ExampleThread t1 = new ExampleThread(42);
ExampleThread t2 = new ExampleThread(43);
ExampleThread t3 = new ExampleThread(44);
t1.start();
t2.start();
t3.start();
System.out.println(“All threads have terminated.”);
}
}
gtl1–R593 W3L1 — Java Threads 2016–02–08 11 / 17
Concurrency in Java Examples
Execution Result
A possible result is as follows:
This is thread 42
This is thread 43
All threads have terminated.
This is thread 44
The statements in main() after the start() statements can interleave
with the statements of the started threads.
The result is non-deterministic, and can differ with each run of the
program.
gtl1–R593 W3L1 — Java Threads 2016–02–08 12 / 17
Concurrency in Java Examples
Runnable example
class ExampleRunnable implements Runnable {
int _id;
ExampleRunnable(int id){ _id = id; }
public void run() {
System.out.println(“This is runnable thread: ” + _id);
}
public static void main(String[] args) {
Thread t1 = new Thread(new ExampleRunnable(42));
Thread t2 = new Thread(new ExampleRunnable(43));
Thread t3 = new Thread(new ExampleRunnable(44));
t1.start();
t2.start();
t3.start();
System.out.println(“All threads have terminated.”); }
}
gtl1–R593 W3L1 — Java Threads 2016–02–08 13 / 17
ThreadPoolExecutor Use ThreadPools to group and control threads
ThreadPoolExecutor
In order to control or synchronise the behaviour of threads, a thread
pool can be used
A thread pool represents a set of threads.
A thread can access info about its own thread pool.
Methods of Java ThreadPoolExecutor class include
Factory methods for creating new thread pools, e.g.
ex = (ThreadPoolExecutor)
Executors.newFixedThreadPoolExecutor(5);
int getActiveCount(): Returns the number of active threads in this
thread pool
Add a thread t to a pool ex by calling
Thread t = new Thread(Runnable r);
ex.execute(t);
gtl1–R593 W3L1 — Java Threads 2016–02–08 14 / 17
ThreadPoolExecutor ThreadPool example
ThreadPool Example
public class ThreadPoolMember implements Runnable {
// public class ThreadPoolMember extends Thread {
int _id;
ThreadPoolMember (int id) { _id = id; }
public void run() {
System.out.println(“This is thread: ” + _id);
try Thread.sleep(500); }
catch(InterruptedException e) {};
System.out.println(“This is thread: “+ _id +” again.”);
try { Thread.sleep(500); }
catch(InterruptedException e) {};
System.out.println(“Thread “+ _id +” has terminated.”);
gtl1–R593 W3L1 — Java Threads 2016–02–08 15 / 17
ThreadPoolExecutor ThreadPool example
ThreadPool Example (Cont’d)
public static void main(String[] args) {
ThreadPoolExecutor ex = (ThreadPoolExecutor) Executors.newFixedThreadPool(5);
for (int i=42; i<=44; ++i) {
ThreadPoolMember t = new ThreadPoolMember(i);
ex.execute(t);
}
System.out.println(ex.getActiveCount()+" threads.");
while (ex.activeCount() > 0) {
try { Thread.sleep(100); } catch(InterruptedException e) {};
}
System.out.println(“All threads have terminated.”);
}
}
Program now outputs “All threads have terminated” only
after all threads actually terminated.
gtl1–R593 W3L1 — Java Threads 2016–02–08 16 / 17
Summary
Summary
Thread in Java can be created via:
Extending Thread class
Implementing Runnable interface
The result of running programs with multiple threads may be
non-deterministic
The Java ThreadPoolExecutor class can be used to collectively
manage the behaviour of threads
(Deprecated ThreadPool interface provides another mechanism to
control groups of threads.)
We have not yet really considered critical sections
gtl1–R593 W3L1 — Java Threads 2016–02–08 17 / 17
Concurrency in Java
Extend Thread class
Implement Runnable interface
Thread methods
Using threads
Examples
ThreadPoolExecutor
Use ThreadPools to group and control threads
ThreadPool example