+ All Categories

Threads

Date post: 02-Jan-2016
Category:
Upload: kameko-rojas
View: 15 times
Download: 0 times
Share this document with a friend
Description:
Threads. Chate Patanothai. Objectives. Define a thread Create separate threads Control the execution of a thread Communicate between threads Protect shared data. What are threads?. An execution context a virtual CPU the code for executing the data A process is a program in execution - PowerPoint PPT Presentation
26
Threads Chate Patanothai
Transcript
Page 1: Threads

Threads

Chate Patanothai

Page 2: Threads

C. Patanothai 31/8/2005

Threads 2

Objectives

• Define a thread• Create separate threads• Control the execution of a thread• Communicate between threads• Protect shared data

Page 3: Threads

C. Patanothai 31/8/2005

Threads 3

What are threads?

• An execution context– a virtual CPU– the code for executing– the data

• A process is a program in execution• A process has one or more threads

Page 4: Threads

C. Patanothai 31/8/2005

Threads 4

Thread code and data

• In Java, the virtual CPU is encapsulated in an instance of the Thread class

• Two threads share the same code when they execute from instances of the same class

• Two threads share the same data when they share access to a common object

Page 5: Threads

C. Patanothai 31/8/2005

Threads 5

Making a thread

• Making you class inherits from Thread– simple– cannot extend from other class

• Creating a new class that implements Runnable interface (preferred)– better OOD– single inheritance– consistency

• Overriding run() method

Page 6: Threads

C. Patanothai 31/8/2005

Threads 6

Creating the thread

• create an instance of Runnable• the Thread class already

implemented Runnable interface

Page 7: Threads

C. Patanothai 31/8/2005

Threads 7

Subclass of Threadpublic class ThreadTester { public static void main(String[] args) { // creating a thread SomeThread t = new SomeThread();

// start the thread t.start(); }}

class SomeThread extends Thread {

public void run() { // code for thread execution }

}

Page 8: Threads

C. Patanothai 31/8/2005

Threads 8

Implementing Runnablepublic class ThreadTester { public static void main(String[] args) { // creating an instance of a Runnable RunningClass rc = new RunningClass(); // creating a new thread for the Runnable instance Thread t = new Thread(rc); // starting the thread t.start(); }}

class RunningClass [extends XXX] implements Runnable {

public void run() { // must be overridden // code for thread execution }}

Page 9: Threads

C. Patanothai 31/8/2005

Threads 9

Starting the Thread

• Using the start method• Placing the thread in runnable state

Page 10: Threads

C. Patanothai 31/8/2005

Threads 10

Basic Thread States

Runnable

Blocked

Running

New Dead

blocking eventunblocked

scheduler

start() run() completes

Page 11: Threads

C. Patanothai 31/8/2005

Threads 11

Sleeping (ZZZZZZZZZZ)

• allow other threads a chance to execute• sleep is a static method in the Thread class• throws InterruptedException

public class Runner implements Runnable { public void run() { while (true) { // do lots of interesting stuff : // Give other threads a chance try { Thread.sleep(10); // time in milliseconds } catch (InterruptedException e) { // This thread’s sleep was interrupted by another thread } } }}

Page 12: Threads

C. Patanothai 31/8/2005

Threads 12

Terminating a Thread

• when a thread completes, it cannot run again

• using a flag to indicate the exit condition

public class Runner implements Runnable {

private boolean done = false; public void run() { while (!done) { . . . } }

public void stopRunning() { done = true; }}

public class ThreadController { private Runner r = new Runner(); private Thread t = new Thread(r);

public void startThread() { t.start(); }

public void stopThread() { t.stopRunning() }}

Page 13: Threads

C. Patanothai 31/8/2005

Threads 13

Basic Control of Threads

• Testing threads:– isAlive()

• Accessing thread priority:– getPriority()– setPriority()

• Putting threads on hold:– Thread.sleep()– join()– Thread.yield()

Page 14: Threads

C. Patanothai 31/8/2005

Threads 14

Thread Priority

• Thread.MIN_PRIORITY (1)• Thread.NORM_PRIORITY (5)• Thread.MAX_PRIORITY (10)

Page 15: Threads

C. Patanothai 31/8/2005

Threads 15

The join Method

• wait until the thread on which the join method is called terminates

public static void main(String[] args) {

Thread t = new Thread(new Runner());

t.start();

. . .

// do stuff in parallel

. . .

// wait for t to finish

try {

t.join();

} catch (InterruptedException e) {

// t came back early

}

// continue this thread

. . .

}

Page 16: Threads

C. Patanothai 31/8/2005

Threads 16

The Thread.yield Method

• give other runnable threads a chance to execute

• places the calling thread into the runnable pool if there are thread(s) in runnable,

• if not, yield does nothing• sleep gives lower priority threads a

chance• yield gives other runnable threads a

chance

Page 17: Threads

C. Patanothai 31/8/2005

Threads 17

Shared datapublic class MyStack {

int idx = 0;

char[] data = new char[6];

public void push(char c) {

data[idx] = c;

idx++;

}

public char pop() {

idx--;

return data[idx];

}

}

• one thread (A) pushing data onto the stack

• one thread (B) popping data off the stack

A just finished push a character, then preempted

B is now in Running

buffer p q

idx = 2 ^

buffer p q r

idx = 2 ^

Page 18: Threads

C. Patanothai 31/8/2005

Threads 18

The Object Lock Flag

• Every object has a “lock flag”• use synchronized to enable

interaction with this flag

Page 19: Threads

C. Patanothai 31/8/2005

Threads 19

Using synchronizedpublic class MyStack { . . . public void push(char c) { synchronized(this) { data[idx] = c; idx++; } } . . .}

public void push(char c) { synchronized(this) { data[idx] = c; idx++; } }

Page 20: Threads

C. Patanothai 31/8/2005

Threads 20

Releasing the Lock Flag

• A thread waiting for the lock flag of an object cannot resume running until it get the flag

• Released when the thread passes the end of the synchronized code block

• Automatically released when a break, return, or exception is thrown by the synchronized code block

Page 21: Threads

C. Patanothai 31/8/2005

Threads 21

Shared Data

• All access to shared data should be synchronized

• Shared data protected by synchronized should be private

Page 22: Threads

C. Patanothai 31/8/2005

Threads 22

Thread States (synchronized)

Runnable

Blocked

Running

New Dead

blocking eventunblocked

scheduler

start() run() completes

Blocked in object’s

lock pool

synchronizedacquires lock

Page 23: Threads

C. Patanothai 31/8/2005

Threads 23

Deadlock

• Two threads waiting for a lock from other

• no detection or avoidance by Java• Can be avoided by

– the order to obtain locks– applying the order throughout the

program– releasing the lock in the reverse order

Page 24: Threads

C. Patanothai 31/8/2005

Threads 24

Thread Interaction

• wait and notify• methods from java.lang.Object• if a thread issues a wait call on an object

x, it pauses its execution until another thread issues a notify call on the same object x

• the thread MUST have the lock for that object (wait and notify are called only from within a synchronized block on the instance being called)

Page 25: Threads

C. Patanothai 31/8/2005

Threads 25

The pools

• Wait pool– execute wait()

• Lock pool– thread moved from

wait pool– notify()

• arbitrary thread

– notifyAll()• all threads

Running

Blocked in object’s

lock pool

synchronized

Blocked in object’s

wait pool

wait()[must have lock]/release lock

notify()orinterrupt()

Page 26: Threads

C. Patanothai 31/8/2005

Threads 26

Thread States (wait/notify)

Runnable

Blocked

Running

New Dead

blocking eventunblocked

scheduler

start() run() completes

Blocked in object’s

lock pool

synchronizedacquires lock

Blocked in object’s

wait pool

wait()[must have lock]/release lock

notify()orinterrupt()


Recommended