1 tutorial: csi 3310 dewan tanvir ahmed site, uofo

36
1 Tutorial: CSI 3310 Dewan Tanvir Ahmed SITE, UofO

Upload: preston-willis

Post on 02-Jan-2016

217 views

Category:

Documents


1 download

TRANSCRIPT

Page 1: 1 Tutorial: CSI 3310 Dewan Tanvir Ahmed SITE, UofO

1

Tutorial: CSI 3310

Dewan Tanvir AhmedSITE, UofO

Page 2: 1 Tutorial: CSI 3310 Dewan Tanvir Ahmed SITE, UofO

2

Today’s Objective

• What is a Thread? • A thread is a single sequential flow of control within a program.

Page 3: 1 Tutorial: CSI 3310 Dewan Tanvir Ahmed SITE, UofO

3

multithread

Page 4: 1 Tutorial: CSI 3310 Dewan Tanvir Ahmed SITE, UofO

4

The lifecycle of a thread

Page 5: 1 Tutorial: CSI 3310 Dewan Tanvir Ahmed SITE, UofO

5

Class Thread

• java.lang.Thread• Constructors

– public Thread()• Allocates a new Thread object. • Automatically generated names are of the form "Thread-"+n, where n is

an integer.

– public Thread(Runnable target) • target - the object whose run method is called. • The Runnable interface should be implemented by any class whose

instances are intended to be executed by a thread. • The class must define a method of no arguments called run.

– public Thread(String threadName)– public Thread(Runnable target, String  threadName)

Page 6: 1 Tutorial: CSI 3310 Dewan Tanvir Ahmed SITE, UofO

6

Methods of Class Thread

• public void start() – Causes this thread to begin execution; – the Java Virtual Machine calls the run method of this thread. – The result is that two threads are running concurrently: the current

thread (which returns from the call to the start method) and the other thread (which executes its run method).

• public void run() – If this thread was constructed using a separate Runnable run

object, then that Runnable object's run method is called; – otherwise, this method does nothing and returns. – Subclasses of Thread should override this method.

Page 7: 1 Tutorial: CSI 3310 Dewan Tanvir Ahmed SITE, UofO

7

Methods of Class Thread

• public static void sleep(long milliseconds) throws InterruptedException– Causes the currently executing thread to sleep (temporarily cease

execution) for the specified number of milliseconds. The thread does not lose ownership of any monitors.

try {

Thread.sleep(1000);

} catch (InterruptedException e) {

……

}

Page 8: 1 Tutorial: CSI 3310 Dewan Tanvir Ahmed SITE, UofO

8

Create a thread (1)• extend the class Thread and override the run() method• Example

class Test extends Thread {

public void run() { ……}

}

public static void main(String args[]) {……

Test t = new Test ();

t.start();

……

}

Page 9: 1 Tutorial: CSI 3310 Dewan Tanvir Ahmed SITE, UofO

9

Pure exampleclass MyThread1 extends Thread {

static String message[] = {"Java","is","hot,","aromatic,","and","invigorating."};

public MyThread1(String id) {super(id);

}public void run() {

String name = getName();for(int i=0; i<message.length;++i) {

randomWait();System.out.println(name+message[i]);

}}void randomWait() {

try {sleep((long)(1000*Math.random()));

}catch (InterruptedException x) {System.out.println("Interrupted!");

}}

Page 10: 1 Tutorial: CSI 3310 Dewan Tanvir Ahmed SITE, UofO

10

example (cont)public static void main(String args[]) {

MyThread1 thread1 = new MyThread1("thread1: ");MyThread1 thread2 = new MyThread1("thread2: ");thread1.start();thread2.start();boolean thread1IsAlive = true;boolean thread2IsAlive = true;do {

if(thread1IsAlive && !thread1.isAlive()) {thread1IsAlive = false;System.out.println("Thread 1 is dead.");

}if(thread2IsAlive && !thread2.isAlive()) {

thread2IsAlive = false;System.out.println("Thread 2 is dead.");

}}while(thread1IsAlive || thread2IsAlive);

}}

Page 11: 1 Tutorial: CSI 3310 Dewan Tanvir Ahmed SITE, UofO

11

resultsthread1: Javathread2: Javathread1: isthread1: hot,thread2: isthread1: aromatic,thread2: hot,thread1: andthread2: aromatic,thread1: invigorating.Thread 1 is dead.thread2: andthread2: invigorating.Thread 2 is dead.

thread2: Javathread1: Javathread1: isthread2: isthread2: hot,thread2: aromatic,thread2: andthread2: invigorating.Thread 2 is dead.thread1: hot,thread1: aromatic,thread1: andthread1: invigorating.Thread 1 is dead.

thread1: Javathread1: isthread1: hot,thread1: aromatic,thread2: Javathread1: andthread1: invigorating.Thread 1 is dead.thread2: isthread2: hot,thread2: aromatic,thread2: andthread2: invigorating.Thread 2 is dead.

Page 12: 1 Tutorial: CSI 3310 Dewan Tanvir Ahmed SITE, UofO

12

Interface Runnable

• java.lang.Runnable– The Runnable interface should be implemented by any class whose

instances are intended to be executed by a thread. – The class must define a method of no arguments called run. – Runnable provides the means for a class to be active while not

subclassing Thread. – A class that implements Runnable can run without subclassing

Thread by instantiating a Thread instance and passing itself in as the target.

– In most cases, the Runnable interface should be used if you are only planning to override the run() method and no other Thread methods. This is important because classes should not be subclassed unless the programmer intends on modifying or enhancing the fundamental behavior of the class.

• Method– public void run()

Page 13: 1 Tutorial: CSI 3310 Dewan Tanvir Ahmed SITE, UofO

13

Runnable Interface

• Multithreading in a class that extends a class– A class cannot extend more than one class– Implements Runnable for multithreading support

• Runnable object grouped with a Thread object

Page 14: 1 Tutorial: CSI 3310 Dewan Tanvir Ahmed SITE, UofO

14

Create a thread (2)• implement the Runnable interface

class Test implements Runnable {public void run() { ……}

}public static void main(String args[]) {

……Test t = new Test ();Thread th = new Thread(t);th.start();……

}

Page 15: 1 Tutorial: CSI 3310 Dewan Tanvir Ahmed SITE, UofO

15

Pure exampleclass MyThread2 {

public static void main(String args[]) {Thread thread1 = new Thread(new MyClass("thread1: "));Thread thread2 = new Thread(new MyClass("thread2: "));thread1.start();thread2.start();boolean thread1IsAlive = true;boolean thread2IsAlive = true;do {

if(thread1IsAlive && !thread1.isAlive()) {thread1IsAlive = false;System.out.println("Thread 1 is dead.");

}if(thread2IsAlive && !thread2.isAlive()) {

thread2IsAlive = false;System.out.println("Thread 2 is dead.");

}}while(thread1IsAlive || thread2IsAlive);

}}

Page 16: 1 Tutorial: CSI 3310 Dewan Tanvir Ahmed SITE, UofO

16

example (cont)class MyClass implements Runnable {

static String message[] = {"Java","is","hot,","aromatic,","and","invigorating."};String name;public MyClass(String id) {

name = id;}public void run() {

for(int i=0; i<message.length;++i) {randomWait();System.out.println(name+message[i]);

}}void randomWait() {

try {Thread.currentThread().sleep((long)(3000*Math.random()));

}catch (InterruptedException x) {System.out.println("Interrupted!");

}}

}

Page 17: 1 Tutorial: CSI 3310 Dewan Tanvir Ahmed SITE, UofO

17

resultsthread1: Javathread2: Javathread1: isthread1: hot,thread2: isthread1: aromatic,thread2: hot,thread1: andthread1: invigorating.Thread 1 is dead.thread2: aromatic,thread2: andthread2: invigorating.Thread 2 is dead.

thread2: Javathread1: Javathread2: isthread1: isthread2: hot,thread2: aromatic,thread1: hot,thread1: aromatic,thread2: andthread2: invigorating.Thread 2 is dead.thread1: andthread1: invigorating.Thread 1 is dead.

thread1: Javathread2: Javathread2: isthread2: hot,thread2: aromatic,thread1: isthread1: hot,thread2: andthread1: aromatic,thread2: invigorating.Thread 2 is dead.thread1: andthread1: invigorating.Thread 1 is dead.

Page 18: 1 Tutorial: CSI 3310 Dewan Tanvir Ahmed SITE, UofO

18

exampleimport java.io.*;import java.lang.*;import java.lang.Thread.*;

class Processus extends Thread { static int mem; Processus(String name) {

super(); // call of the super class constructor (Thread) setName(name); // setting the name } /* redefinition of the run() method */ public void run() { for(int i=0; i<10; i++) { System.out.println(getName()+"("+i+") = "+(mem++));

try {sleep((int)(Math.random()*1000));

} catch(InterruptedException x) {System.out.println("Thread "+getName()+"interrupted !");

} } }}

Page 19: 1 Tutorial: CSI 3310 Dewan Tanvir Ahmed SITE, UofO

19

exampleimport java.io.*;import java.lang.*;

class TestProc {

public static void main(String args[]) { Processus p1 = new Processus("p1"); Processus p2 = new Processus("p2"); Processus p3 = new Processus("p3"); p1.start(); p2.start(); p3.start();

for(int i=0; i<10; i++) { System.out.println("main("+i+")"); } }}

Page 20: 1 Tutorial: CSI 3310 Dewan Tanvir Ahmed SITE, UofO

20

exampleimport java.io.*;import java.lang.*;class ThreadRunnable implements Runnable {

static int mem;Thread T;ThreadRunnable(String name) {

T = new Thread(this); // creation of a new Thread setName(name); // setting of the name

}public void run() {

for(int i=0; i<10; i++) { System.out.println(getName()+"("+i+") = "+(mem++));

try { T.sleep((int)Math.random()*1000); } catch(InterruptedException e) { System.out.println("Sleep

interrupted !"); } }

}public void start() {

T.start();}public String getName() {

return(T.getName());}public void setName(String name) {

T.setName(name); }}

Page 21: 1 Tutorial: CSI 3310 Dewan Tanvir Ahmed SITE, UofO

21

exampleimport java.io.*;import java.lang.*;

class TestRunnable {

public static void main(String args[]) { ThreadRunnable p1 = new ThreadRunnable("p1"); ThreadRunnable p2 = new ThreadRunnable("p2"); ThreadRunnable p3 = new ThreadRunnable("p3");

p1.start(); p2.start(); p3.start();

for(int i=0; i<10; i++) { System.out.println("main("+i+")"); } }}

Page 22: 1 Tutorial: CSI 3310 Dewan Tanvir Ahmed SITE, UofO

22

Methods are deprecated• suspend()

– Forces the thread to stop executing.

• resume() – Resumes a suspended thread.

• stop()– Forces the thread to stop executing.

• Unsafe• Cause the data lose or deadlock

Page 23: 1 Tutorial: CSI 3310 Dewan Tanvir Ahmed SITE, UofO

23

Instead of stop()

• stop()– replaced by code that simply modifies some variable to indicate that

the target thread should stop running

Page 24: 1 Tutorial: CSI 3310 Dewan Tanvir Ahmed SITE, UofO

24

example

• Using stop()

private Thread blinker;

public void start() {

blinker = new Thread(this);

blinker.start();

}

public void stop() {

blinker.stop(); // UNSAFE!

}

Page 25: 1 Tutorial: CSI 3310 Dewan Tanvir Ahmed SITE, UofO

27

Instead of suspend() and resume()

• suspend() – wait()

• Causes current thread to wait until another thread invokes the notify() method or the notifyAll() method for this object.

• The current thread must own this object's monitor.

• The thread releases ownership of this monitor and waits until another thread notifies threads waiting on this object's monitor to wake up either through a call to the notify method or the notifyAll method.

• The thread then waits until it can re-obtain ownership of the monitor and resumes execution.

• This method should only be called by a thread that is the owner of this object's monitor.

Page 26: 1 Tutorial: CSI 3310 Dewan Tanvir Ahmed SITE, UofO

28

Instead of suspend() and resume() – cont..

• resume()– notify()

• Wakes up a single thread that is waiting on this object's monitor. • If any threads are waiting on this object, one of them is chosen to

be awakened. The choice is arbitrary and occurs at the discretion of the implementation.

• A thread waits on an object's monitor by calling one of the wait methods.

• The awakened thread will not be able to proceed until the current thread relinquishes the lock on this object. The awakened thread will compete in the usual manner with any other threads that might be actively competing to synchronize on this object; for example, the awakened thread enjoys no reliable privilege or disadvantage in being the next thread to lock this object.

Page 27: 1 Tutorial: CSI 3310 Dewan Tanvir Ahmed SITE, UofO

29

Thread priority• A thread's priority affects when it runs in relation to other

threads• MIN_PRIORITY(1)

MAX_PRIORITY(10)NORM_PRIORITY (5) - default

Page 28: 1 Tutorial: CSI 3310 Dewan Tanvir Ahmed SITE, UofO

30

Thread priority• setPriority(int newPriority)

– Changes the priority of this thread

• getPriority() – Returns this thread's priority

• yield()– Causes the currently executing thread object to temporarily pause

and allow other threads to execute

Page 29: 1 Tutorial: CSI 3310 Dewan Tanvir Ahmed SITE, UofO

31

priority scheduling• From highest to lowest• Same priority

– run in a round-robin fashion– yield()

• preemptive

Page 30: 1 Tutorial: CSI 3310 Dewan Tanvir Ahmed SITE, UofO

32

priority scheduling

Page 31: 1 Tutorial: CSI 3310 Dewan Tanvir Ahmed SITE, UofO

33

Exampleimport java.io.*;

public class PriorityTest { static int NUM_THREADS = 4; static final int MAX_COUNTER = 2000000; static boolean yield = true; static int counter[] = new int[NUM_THREADS]; public static void main (String args[]) { PrintWriter out = new PrintWriter (System.out, true); int numIntervals = 10; if (args.length > 0) yield = false; out.println ("Using yield()? " + (yield ? "YES" : "NO")); for (int i = 0; i < NUM_THREADS; i++) (new PrTestThread ((i > 1) ? 4 : (i + 1), i)).start(); ThreadInfo.printAllThreadInfo(); out.println();

Page 32: 1 Tutorial: CSI 3310 Dewan Tanvir Ahmed SITE, UofO

34

Example(cont) // repeatedly print out the counter values int step = 0; while (true) { boolean allDone = true; try { Thread.sleep (300); } catch (InterruptedException e) { } out.print ("Step " + (step++) + ": COUNTERS:"); for (int j = 0; j < NUM_THREADS; j++) { out.print (" " + counter[j]); if (counter[j] < MAX_COUNTER) allDone = false; } out.println(); if (allDone) break; } System.exit(0); }}

Page 33: 1 Tutorial: CSI 3310 Dewan Tanvir Ahmed SITE, UofO

35

Example(cont)class PrTestThread extends Thread { int id; PrTestThread (int priority, int id) {

super ("PrTestThread#" + id); this.id = id; setPriority(priority);

} public void run() { for (int i = 0; i <= PriorityTest.MAX_COUNTER; i++) { if (((i % 3000) == 0) && PriorityTest.yield) yield(); PriorityTest.counter[id] = i; } }}

Page 34: 1 Tutorial: CSI 3310 Dewan Tanvir Ahmed SITE, UofO

36

Thread Synchronization

• Java uses monitors for thread synchronization• The sychronized keyword

– Every synchronized method of an object has a monitor– One thread inside a synchronized method at a time– All other threads block until method finishes– Next highest priority thread runs when method finishes

Page 35: 1 Tutorial: CSI 3310 Dewan Tanvir Ahmed SITE, UofO

37

Producer/Consumer Relationship without Synchronization

• Buffer– Shared memory region

• Producer thread– Calls produce method to add item to buffer– Calls wait if consumer has not read last message in buffer– Writes to empty buffer and calls notify for consumer

• Consumer thread– Reads message from buffer– Calls wait if buffer empty

• Synchronize threads to avoid corrupted data

Page 36: 1 Tutorial: CSI 3310 Dewan Tanvir Ahmed SITE, UofO

38

Thank You!