1
Multithreading in Java
Java Threads
2
Contents
• Introduction
• Definition and elements of concurrent
programming
• Threads
• Java threads
• Java Thread API & issues
• Exercises
3
Concurrent programming
• Concurrent programming is the name given to
programming notation and techniques for expressing
potential parallelism and solving the resulting
synchronization and communication problems.
• We need concurrency to model the parallelism in the
real world
4
Elements of concurrent programming
• Expressing:
– potential concurrency
• Processes, threads, …
– Synchronization/concurrency control
• Locks, semaphors, monitors, …
– Communication
• Shared memory, message passing, …
5
Java Concurrency Model
• Java supports threads
– Threads execute within a single JVM
– Native threads map a single Java thread to an
OS thread
– Green threads adopt the thread library approach
(threads are invisible to the OS)
• Java adopts the active object approach
– i.e. an object which can have activity
independent of the rest of the application
6
java.lang.Thread
• = JVM-provided Active Object
– Each instance is/has one thread
• Executes the run() method in a new thread when
start() is called
• Thread ends when run() completes (returns)
• Concurrent code specified by either
– Subclassing Thread and overriding run() or
– Implementing java.lang.Runnable (defining run())
and passing to Thread constructor
7
Threads in Java
java.lang.Thread
void run()
void start()
...
Thread()
Thread(Runnable target)
subclass
association
MyThread
void run()
{
...
}
parameter to
MyRunnableObject
void run()
{
...
}
implements
java.lang.Runnable
(interface)
void run()
8
Simple Test: what will they print?
• public class Print10 extends Thread {
public void run() {
// overriden
for (int i=0; i<10; i++) {
System.out.println(i);
try { sleep(1000);
}catch (InterruptedException ie) {}
}
}
}
• (b)
new Print10().run();
new Print10().run();
• (a)
new Print10().start();
new Print10().start();
9
Concurrent solution (Thread)(Java pseudo code)
public class Controller1 extends Thread {
public void run() {
while(true) {
// read value
// write value
}
}
}
public class Controller2 extends Thread {
public void run() {
while(true) {
// read value
//
}
}
}
new Controller1().start();
new Controller2().start();
10
Concurrent solution (Runnable) (Java pseudo code)
public class Controller1 implements Runnable {
public void run() {
while(true) {
// read
// write
}
}
}
public class Controller2 implements Runnable {
public void run() {
while(true) {
// reead
// write
}
}
}
new Thread(new Controller1()).start();
new Thread(new Controller2()).start();
11
Concurrent solution (anonymous subclass) (Java
pseudo code)
new Thread() {
public void run() {
while(true) {
//read
// write
}
}
}.start();
new Thread() {
public void run() {
while(true) {
// read
// write
}
}
}.start();
12
Other java thread operations
• Thread.sleep(int ms) – calling thread waits for
time (at least ms) to pass
• t.join()/(int ms) – wait for t to finish; optionally
give up waiting after ms
• Thread.currentThread() - return reference to
thread executing that call
• t.interrupt() – interrupt (next) blocking operation
in that thread (see later in course)
13
Java thread class
• class Thread implements Runnable {
/* static methods - apply to current thread */
public static native Thread currentThread();
/* pause thead for at least this long */
public static native void sleep(long millis)
throws InterruptedException;
/* constructors (there are many others) */
public Thread();
public Thread(Runnable target);
/* start thread executing */
public synchronized native void start();
/* over-riden function to execute (else calls run() on target) */
public void run();
• /* started and not yet stopped */
public final native boolean isAlive();
/* interrupt thread, e.g. in wait, sleep */
public void interrupt();
/* wait for thread to finish */
public final synchronized void join(long millis)
throws InterruptedException;
}
14
Other Java Thread issues
• Preemption/time-slicing of busy threads
– Not implemented in all JVMs
– Else requires cooperative multitasking (e.g.
calls to Thread.sleep(0)).
• Resource Requirements
– Stack (native & Java)
• E.g. ~128MB virtual memory per thread
• See java.nio for newer non-blocking IO options
(need fewer threads, e.g. for large web servers)
15
Java thread states
• Java thread life-cycle (Thread States):
16
Summary
• Concurrently executable code expressed as
run() method of Runnable or Thread
• Executed concurrently by a Thread object
after start()
• Runs to completion unless stop()ed Blocked
by sleeping, locking, wait, join

1. learning programming with JavaThreads.pdf

  • 1.
  • 2.
    2 Contents • Introduction • Definitionand elements of concurrent programming • Threads • Java threads • Java Thread API & issues • Exercises
  • 3.
    3 Concurrent programming • Concurrentprogramming is the name given to programming notation and techniques for expressing potential parallelism and solving the resulting synchronization and communication problems. • We need concurrency to model the parallelism in the real world
  • 4.
    4 Elements of concurrentprogramming • Expressing: – potential concurrency • Processes, threads, … – Synchronization/concurrency control • Locks, semaphors, monitors, … – Communication • Shared memory, message passing, …
  • 5.
    5 Java Concurrency Model •Java supports threads – Threads execute within a single JVM – Native threads map a single Java thread to an OS thread – Green threads adopt the thread library approach (threads are invisible to the OS) • Java adopts the active object approach – i.e. an object which can have activity independent of the rest of the application
  • 6.
    6 java.lang.Thread • = JVM-providedActive Object – Each instance is/has one thread • Executes the run() method in a new thread when start() is called • Thread ends when run() completes (returns) • Concurrent code specified by either – Subclassing Thread and overriding run() or – Implementing java.lang.Runnable (defining run()) and passing to Thread constructor
  • 7.
    7 Threads in Java java.lang.Thread voidrun() void start() ... Thread() Thread(Runnable target) subclass association MyThread void run() { ... } parameter to MyRunnableObject void run() { ... } implements java.lang.Runnable (interface) void run()
  • 8.
    8 Simple Test: whatwill they print? • public class Print10 extends Thread { public void run() { // overriden for (int i=0; i<10; i++) { System.out.println(i); try { sleep(1000); }catch (InterruptedException ie) {} } } } • (b) new Print10().run(); new Print10().run(); • (a) new Print10().start(); new Print10().start();
  • 9.
    9 Concurrent solution (Thread)(Javapseudo code) public class Controller1 extends Thread { public void run() { while(true) { // read value // write value } } } public class Controller2 extends Thread { public void run() { while(true) { // read value // } } } new Controller1().start(); new Controller2().start();
  • 10.
    10 Concurrent solution (Runnable)(Java pseudo code) public class Controller1 implements Runnable { public void run() { while(true) { // read // write } } } public class Controller2 implements Runnable { public void run() { while(true) { // reead // write } } } new Thread(new Controller1()).start(); new Thread(new Controller2()).start();
  • 11.
    11 Concurrent solution (anonymoussubclass) (Java pseudo code) new Thread() { public void run() { while(true) { //read // write } } }.start(); new Thread() { public void run() { while(true) { // read // write } } }.start();
  • 12.
    12 Other java threadoperations • Thread.sleep(int ms) – calling thread waits for time (at least ms) to pass • t.join()/(int ms) – wait for t to finish; optionally give up waiting after ms • Thread.currentThread() - return reference to thread executing that call • t.interrupt() – interrupt (next) blocking operation in that thread (see later in course)
  • 13.
    13 Java thread class •class Thread implements Runnable { /* static methods - apply to current thread */ public static native Thread currentThread(); /* pause thead for at least this long */ public static native void sleep(long millis) throws InterruptedException; /* constructors (there are many others) */ public Thread(); public Thread(Runnable target); /* start thread executing */ public synchronized native void start(); /* over-riden function to execute (else calls run() on target) */ public void run(); • /* started and not yet stopped */ public final native boolean isAlive(); /* interrupt thread, e.g. in wait, sleep */ public void interrupt(); /* wait for thread to finish */ public final synchronized void join(long millis) throws InterruptedException; }
  • 14.
    14 Other Java Threadissues • Preemption/time-slicing of busy threads – Not implemented in all JVMs – Else requires cooperative multitasking (e.g. calls to Thread.sleep(0)). • Resource Requirements – Stack (native & Java) • E.g. ~128MB virtual memory per thread • See java.nio for newer non-blocking IO options (need fewer threads, e.g. for large web servers)
  • 15.
    15 Java thread states •Java thread life-cycle (Thread States):
  • 16.
    16 Summary • Concurrently executablecode expressed as run() method of Runnable or Thread • Executed concurrently by a Thread object after start() • Runs to completion unless stop()ed Blocked by sleeping, locking, wait, join