32
Threads Just Java: C10–pages 251- C11–pages 275-

Threads Just Java: C10–pages 251- C11–pages 275-

Embed Size (px)

Citation preview

Page 1: Threads Just Java: C10–pages 251- C11–pages 275-

Threads

Just Java: C10–pages 251-

C11–pages 275-

Page 2: Threads Just Java: C10–pages 251- C11–pages 275-

Threads SEA (WA) 2

What is a Thread?

• A single thread of control/execution– the normal sequential execution

Start

Finish

Page 3: Threads Just Java: C10–pages 251- C11–pages 275-

Threads SEA (WA) 3

Why would you want more?

• Need to do several things at the same time

– Eg Java’s Garbage Collector

• Client/server

• Daemons

• Note:

– Java is one of the few languages with threads

Page 4: Threads Just Java: C10–pages 251- C11–pages 275-

Threads SEA (WA) 4

Unix

• Allows forking of new processes– ie multi-processing

Start

Finish

Page 5: Threads Just Java: C10–pages 251- C11–pages 275-

Threads SEA (WA) 5

Multiple threads

• Forking is quite expensive• Instead have lightweight processes

AKA threads

• Several threads in a single program,

• “running” at the same time and,

• performing parts of the task.

Page 6: Threads Just Java: C10–pages 251- C11–pages 275-

Threads SEA (WA) 6

Notice• There is only one “program” or “process”• The threads share that context• Each thread has its own

– Program counter– Stack– (and thread local storage—ThreadsLocal)

Page 7: Threads Just Java: C10–pages 251- C11–pages 275-

Threads SEA (WA) 7

Option #1

• Subclass the Thread class

– Defined in java.lang package

• Override the run method

Page 8: Threads Just Java: C10–pages 251- C11–pages 275-

Threads SEA (WA) 8

public class MyThread extends Thread { public MyThread(String str) { super(str); }

public void run() { for (int i = 0; i < 5; i++) { System.out.println(getName() + " " + i ); try { sleep((long)(Math.random() * 1000)); } catch (InterruptedException e) {} } System.out.println("End " + getName()); }}

Page 9: Threads Just Java: C10–pages 251- C11–pages 275-

Threads SEA (WA) 9

public class TestThreads { public static void main (String[] args) { new MyThread("A").start(); new MyThread("B").start(); }}

C:\lab4> javac MyThreads.javaC:\lab4> java TestThreads

Page 10: Threads Just Java: C10–pages 251- C11–pages 275-

Threads SEA (WA) 10

Option #2

• Define a class that– implements the Runnable interface– from java.lang package

• Provide a definition of the run method• Eg an Applet—already using extends

extends JApplet

implements Runnable

• Need to get a runnable object

new Thread( new myRunnable() )

Page 11: Threads Just Java: C10–pages 251- C11–pages 275-

Threads SEA (WA) 11

class MyRunnable implements Runnable {

public void run() {

System.out.println("MyRunnable is running");

try { sleep(1000); }

catch (InterruptedException ie) { }

}

public static void main(String [] args) {

Thread t = new Thread( new MyRunnable() );

t.start();

}

}

Page 12: Threads Just Java: C10–pages 251- C11–pages 275-

Threads SEA (WA) 12

Whoops!

• This won’t compile

• Why?

– It is not a subclass of Threads and so

– Has no implementation of sleep

(and also this means the exception is not thrown)

Page 13: Threads Just Java: C10–pages 251- C11–pages 275-

Threads SEA (WA) 13

class MyRunnable implements Runnable {

public void run() {

System.out.println("MyRunnable is running");

try { sleep(1000); }

catch (InterruptedException ie) { }

}

public static void main(String [] args) {

Thread t = new Thread( new MyRunnable() );

t.start();

}

}

Page 14: Threads Just Java: C10–pages 251- C11–pages 275-

Threads SEA (WA) 14

Need to get thread

Thread t = Thread.currentThread();

• This is a static (classic?) method in Threads

• Then you can say:

try { t.sleep(1000); }

catch (InterruptedException ie) { }

Page 15: Threads Just Java: C10–pages 251- C11–pages 275-

Threads SEA (WA) 15

class MyRunnable2 implements Runnable {

public void run() {

System.out.println("MyRunnable2 is running");

Thread t = Thread.currentThread();

try { t.sleep(1000); }

catch (InterruptedException ie) { }

}

public static void main(String [] args) {

Thread t = new Thread( new MyRunnable2() );

t.start();

}

}

Page 16: Threads Just Java: C10–pages 251- C11–pages 275-

Threads SEA (WA) 16

Thread life cycle

• Create a threadnew MyThread("One")

• Starting a threadaThread.start()

• Creates system resources to run the thread• Schedules the thread to be runnable• Calls the thread's run method.

Page 17: Threads Just Java: C10–pages 251- C11–pages 275-

Threads SEA (WA) 17

new

running

sleepingwaiting I/O blocked

runnable• yield

• End of quantum

• interrupt

Page 18: Threads Just Java: C10–pages 251- C11–pages 275-

Threads SEA (WA) 18

Becoming runnable

• start() is called on the thread

– and this then calls run()

• Time set for sleep ends

• Another object uses notify or notifyAll

• I/O completes

Page 19: Threads Just Java: C10–pages 251- C11–pages 275-

Threads SEA (WA) 19

Becoming Not runnable

• Calls the sleep() method

• Calls the wait() method

– for a specific condition to be satisfied

• Calls the yield() method

• Blocks on I/O

Page 20: Threads Just Java: C10–pages 251- C11–pages 275-

Threads SEA (WA) 20

How do threads die?

• They just complete– Ends (falls through the })– a return is executed– an Exception is thrown

public void run() { int i = 0; while (i < 10) { System.out.println("i = " + i++); } }

Page 21: Threads Just Java: C10–pages 251- C11–pages 275-

Threads SEA (WA) 21

Priority

• Threads have a priority from:lowest MIN_PRIORITY — 1

highest MAX_PRIORITY — 10

t1.setPriority( t1.getPriority() +1);• Priority starts as the same as parent’s• Higher priority threads pre-empt lower ones• Equal priority—?

– Depends on whether threads are time-sliced– Can also use yield()

Page 22: Threads Just Java: C10–pages 251- C11–pages 275-

Threads SEA (WA) 22

Kinds of Threads Programming

• No interaction

• Threads work on part of the whole problem

• Act on shared data—mutual exclusion

• Communicating data

– Producer-Consumer

• Daemons

Page 23: Threads Just Java: C10–pages 251- C11–pages 275-

Threads SEA (WA) 23

Mutual exclusion

• Eg bank balance– Credit thread– Debit thread

Page 24: Threads Just Java: C10–pages 251- C11–pages 275-

Threads SEA (WA) 24

Producer-Consumer

producer

consumer

0

1

2

34

5

6

7

See pages 282-

put()

get()

Page 25: Threads Just Java: C10–pages 251- C11–pages 275-

Threads SEA (WA) 25

#1—Locking methods()

public class CP {

private int [] circBuffer;

public synchronized int get() {

}

public synchronized void put(int value) {

}

}

// locked by Consumer

// unlocked by Consumer

// locked by Producer

// unlocked by Producer

Page 26: Threads Just Java: C10–pages 251- C11–pages 275-

Threads SEA (WA) 26

• Note that this locks the object on which the method is acting

• That is:– Each object has an associated monitor

• This is an old idea from Prof. Hoare at Oxford

Page 27: Threads Just Java: C10–pages 251- C11–pages 275-

Threads SEA (WA) 27

What if the buffer is empty?

Consumer must wait

try {// wait for Producer to put value

wait(); } catch (InterruptedException e) { }…

notify(); // notify Producerreturn value;

NB should be in a while (empty) { }

Page 28: Threads Just Java: C10–pages 251- C11–pages 275-

Threads SEA (WA) 28

What if the buffer is full?

Producer must wait

try { // wait for Consumer to get valuewait();

} catch (InterruptedException e) { }

…notify(); // notify Consumer

NB should be in a while (full) { }

Page 29: Threads Just Java: C10–pages 251- C11–pages 275-

Threads SEA (WA) 29

#2—locking a classic Method

static synchronized void update() {

• All objects in that class would be controlled

Page 30: Threads Just Java: C10–pages 251- C11–pages 275-

Threads SEA (WA) 30

#3—locking a block

• Need to lock the block on an object

static Object lock = new Object()

synchronized (lock) {

… block of statements

}

Page 31: Threads Just Java: C10–pages 251- C11–pages 275-

Threads SEA (WA) 31

Joining Threads

public final void join() throws InterruptedException

public final void join(long milliseconds) throws InterruptedException

public final void join(long milliseconds, int nanoseconds) throws InterruptedException

• For example:

t.join()• waits for the Thread t to finish before

continuing.

Page 32: Threads Just Java: C10–pages 251- C11–pages 275-

Threads SEA (WA) 32

When does the app end?

Java Virtual Machine continues until:

• System.exit(n) is called

– and the security manager permits it.

• All threads (not daemon threads) have died

– returning from the call to the run method

– throwing an exception that propagates beyond the

run method.