You are on page 1of 27

MODULE: Threads

• Using threads

• java.lang.Thread

• java.lang.Runnable

• sleep, join, yield

javaprogrammering
When use threads?
• If you have to wait for a resource or an event (such as user input)

• If you want some operation to be independently delayed by some


amount of time

• If you have an independent repetitive operation (such as an


animation)

• If you want to provide simultaneous service for several clients


(e.g. a chat server)

• If you want a responsive user interface

• etc

javaprogrammering
Thread
• For separate, independently running subtasks

• Like a virtual computer, with its own


– CPU
– Code
– Data

• Can share code and / or data with other threads

javaprogrammering
Process vs thread
• Process – a self-contained running program with its own
address space (e.g. running the JVM)

• Thread – (“lightweight process”) a single sequential flow


of control within a process; shares address space

– Native threads – threads are provided by the OS, threads are


scheduled by the OS

– “Green threads” – scheduling done by the JVM

javaprogrammering
Thread scheduler
start() scheduler

t1 t6
t4 t2
t3 t5

runnable threads running threads

javaprogrammering
Runnable
public interface Runnable {
public void run();
}

“The general contract of the method run is that it may


take any action whatsoever.” (Java 2 Std. Ed. API doc.)

javaprogrammering
Yield, ex
class MyClass implements Runnable {
public void run() {
int i = 0;
while (i<100) {
Thread.yield();
System.out.print(” ”+i++);
}
}
}

Note: We cannot be sure that another thread actually is run


( yield() is just a hint to the scheduler )

javaprogrammering
Putting a thread to sleep, ex
class MyClass implements Runnable {
public void run() {
int i = 0;
while (i<100) {
try{
Thread.sleep(100);
} catch(InterruptedException ie){
ie.printStackTrace();
}
System.out.print(” ”+ (i++) );
}
}
}

Note: sleep() will put the thread to sleep, thereby giving other threads a
chance to run (cf. yield())
javaprogrammering
Blocked threads
scheduler

t1 running
runnable t6 threads
threads t4 t2
t3 t5

sleep()

javaprogrammering
Two ways…
Two ways to implement a thread:

1. Implement interface Runnable

2. Extend class Thread

(both uses interface Runnable…)

javaprogrammering
Extending thread, ex
class MyClass extends Thread {
private String message;
MyClass(String message) {
implements Runnable,
this.message = message;
has methods like start() etc.
}
public void run() {
long t = System.currentTimeMillis();
try{ Thread.sleep(5000); }
catch(InterruptedException ie){
ie.printStackTrace();
}
System.out.print(message);
System.out.println(”time = ”+
(System.currentTimeMillis()-t));
}
}

javaprogrammering
Extending thread, ex
public class TestThread {
public static void main(String[] args){
Thread mc = new MyClass("hej");
mc.start();
}
}

javaprogrammering
Implementing Runnable, ex
class MyClass implements Runnable {
private String message;
MyClass(String message) {
this.message = message;
}
public void run() {
try{
Thread.sleep(5000);
} catch(InterruptedException ie){
ie.printStackTrace();
}
System.out.print(message);
}
}

javaprogrammering
Implementing Runnable, ex
public class TestThread {
public static void main(String[] args){
Runnable mc = new MyClass("hej");
Thread t = new Thread(mc);
t.start();
}
}

javaprogrammering
Implement Runnable or Extend Thread?
• Implementing Runnable:
– Better structure, better OO
– Maintains the possibility to extend
– Consistency in code

• Extending Thread:
– Slightly less code
– What about “is-a”…?

javaprogrammering
Interrupting a thread, ex
public static void main(String[] args) {
MyClass mc = new MyClass("hej");
Thread t = new Thread(mc);
t.start();
try{
Thread.sleep(2000);
} catch(InterruptedException ie){
ie.printStackTrace();
}
t.interrupt();
}

javaprogrammering
Waiting for a thread, ex
public static void main(String[] args) {
MyClass mc = new MyClass("hej");
Thread t = new Thread(mc);
t.start();
try{
t.join();
} catch(InterruptedException ie){
ie.printStackTrace();
}
System.out.println(“hopp!”);
}

(Example: The software for an ATM, where several checks have to be done
before we can proceed (card data, code, account balance etc.)

javaprogrammering
Activity diagram
Put card
in slot

Check ID Check
balance

Receive
Synchronization money
bar

javaprogrammering
Stopping a thread
•Use a boolean flag/condition to stop a thread
•Do not use stop() (or any other deprecated metod; see
API doc)

class MyClass implements Runnable {


boolean halt;
public void run() {
halt = false;
while (!halt) {
.
.
}
}
public void setHalt() { halt = true; }
}
javaprogrammering
Naming a thread, ex
class MyClass implements Runnable {
private int i = 0;
public void run() {
while (i<100) {
System.out.println(“Thread: “+
Thread.currentThread().getName()+
“\t i = “ + (i++));
}
}
.
.
public static void main(String[] args) {
Runnable mc = new MyClass();
Thread t = new Thread(mc,”ONE”);
t.start();
}
javaprogrammering
Sharing code, ex
public static void main(String[] args) {

Runnable mc = new MyClass();


Thread t = new Thread(mc);

Runnable mc2 = new MyClass();


Thread t2 = new Thread(mc2);

t.start();
t2.start();
}
javaprogrammering
Sharing code and data, ex
public static void main(String[] args) {

Runnable mc = new MyClass();


Thread t = new Thread(mc);
Thread t2 = new Thread(mc);

t.start();
t2.start();
}

javaprogrammering
Protecting data
• Use synchronized if more than one thread can modify
an object’s data

• Make the data private, and synchronize all methods (or


blocks) in which data are modified (use special mutators to
limit the number of methods to synchronize)

• Observer methods can be synchronized too (but they will


not cause data corruption)

• Synchronize as close to the data as possible

javaprogrammering
Stack, ex
class MyStack {
private[] cArr = new char[10];
private int i;
public void push(char c) {
cArr [i] = c;
i++;
}
public char pull() {
i--;
return cArr[i];
}
}

javaprogrammering
Stack, ex
class MyStack {
private[] cArr = new char[10];
private int i;
public void push(char c) {
synchronized(this) {
cArr [i] = c;
i++;
}
}
public synchronized char pull() {
i--;
return cArr[i];
}
}

javaprogrammering
wait() and notify()
public void push(char c) {
synchronized(this) {
cArr [i] = c;
i++;
this.notify();
}
}

public char pull() throws InterruptedException {


synchronized(this) {
if (i<=0) this.wait();
i--;
return cArr[i];
}
}

javaprogrammering
This document was created with Win2PDF available at http://www.daneprairie.com.
The unregistered version of Win2PDF is for evaluation or non-commercial use only.

You might also like