1 / 36

Tutorial: CSI 3310

Tutorial: CSI 3310. Dewan Tanvir Ahmed SITE, UofO. Today’s Objective. What is a Thread? A thread is a single sequential flow of control within a program. multithread. The lifecycle of a thread. Class Thread. java.lang.Thread Constructors public Thread() Allocates a new Thread object.

Download Presentation

Tutorial: CSI 3310

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  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.

  3. multithread

  4. The lifecycle of a thread

  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(Runnabletarget) • 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(Runnabletarget, StringthreadName)

  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.

  7. Methods of Class Thread • public static void sleep(longmilliseconds) 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) { …… }

  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(); …… }

  9. Pure example class 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!"); } }

  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); } }

  11. results

  12. InterfaceRunnable • 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()

  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

  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(); …… }

  15. Pure example class 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); } }

  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!"); } } }

  17. results

  18. example import 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 !"); } } } }

  19. example import 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+")"); } } }

  20. example import 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); } }

  21. example import 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+")"); } } }

  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

  23. Instead of stop() • stop() • replaced by code that simply modifies some variable to indicate that the target thread should stop running

  24. example • Using stop() private Thread blinker; public void start() { blinker = new Thread(this); blinker.start(); } public void stop() { blinker.stop(); // UNSAFE! }

  25. 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.

  26. 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.

  27. 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

  28. Thread priority • setPriority(intnewPriority) • 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

  29. priority scheduling • From highest to lowest • Same priority • run in a round-robin fashion • yield() • preemptive

  30. priority scheduling

  31. Example import 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();

  32. 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); } }

  33. 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; } } }

  34. 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

  35. 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

  36. Thank You!

More Related