P. 1
Threads and Java

Threads and Java

|Views: 11|Likes:
Published by kuticat

More info:

Published by: kuticat on Feb 04, 2011
Copyright:Attribution Non-commercial


Read on Scribd mobile: iPhone, iPad and Android.
download as PPT, PDF, TXT or read online from Scribd
See more
See less





A presentation by Alex Thomas on 6-Dec 2010


Task, Process ² Background  Concurrency  Threads  LifeCycle of Threads  Thread Priorities & Scheduling  Creating and Executing Threads  Running Threads  Sleeping Threads  Thread Trouble 



An application written ² Start to End
« You

know every step « Know what follows ² Software Lifecycle « Manufacturing processes

Would you be doing only one work at any time?
« Probably

in a class like this.. « Mom·s work?


MANY TASKS ‡ Many activities at the same time As humans we can do probably 4 or 5 activities « How about computers? Early operating system . ± ± ± ‡ ‡ ‡ Once completed you do the next. 1st gen computers ² performed single tasks.DOS (disk OS). Windows 3.1.Round Robin ‡ Why wait for one application? ± ± Not very efficient« Important tasks will on hold 4 . early MAC version. BATCH processing Many Applications .

After the first application has been executed the next application will be executed. One process at one ‡ time. And then the next. 5 . without the previous application your program will not run. So we create batch files Do you want spend time waiting for one task to be completed before your application runs? ‡ Remember.CONCURRENCY (OR MULTI-TASKING) ‡ ‡ ‡ From a command window you can run one ‡ Application at a time.

CONCURRENCY (OR MULTI-TASKING) ‡ Operating System vendors introduced multi-tasking ‡ ‡ ‡ A process for each application to be executed Let many processes run but in equal chunks of time ² Time Slices Each process has been allocated program and data space that will not affect another process 6 .

‡ urgent tasks HIGH priority ‡ Timer expiration ‡ others have LOWER priority 7 . all activities are just set time ‡ Priorities introduced.CONCURRENCY (OR MULTI-TASKING) ‡ ‡ ‡ Operating System vendors introduced multi-tasking Let many applications run but in equal chunks of time ² Time Slices Not good.

an application package will contain many associated executables An OS does not identify the various executables as belonging to one package So they run as different processes.PROCESSES ‡ Many times. ‡ ‡ 8 .

) ‡ Your main application is dependent on another process or application or task ‡ ‡ A layered architecture of application development Waiting for data or state or event ‡ You need Concurrent programming ‡ Flexibility to do things simultaneously ‡ No need to wait ‡ Processes create new process. ‡ Creating new process is heavy ‡ Need more resources ² memory ‡ How about a process that will not require new memory or resources allocated.PROCESSES (CONTD. Something that can run within the same process 9 ‡ Your Application is in waiting state«how long YOU ARE STUCK .


WHY A JAVA THREAD? ‡ ‡ No other languages. have thread support Portability of Java code ‡ Need not worry about any overheads of initialization and managing of resources of each Operating system (JVM does the remaining part). 11 . except ADA.


THREAD STATES ‡ New ± Beginning of Thread life. Not ready for execution until programs moves state to runnable Task is being executed Data dependency on other threads ‡ ‡ ‡ ‡ Runnable ± ± Waiting ± just wait for the other thread completion wait for either expiration of timer or the other thread completion Wait for long time« Timed Waiting (Sleeping thread) ± Blocked ± ‡ Terminated ± End of life 13 .

LET US CREATE THREADS ´ A thread is associated with an instance of a class Thread.asynchronous « Abstract thread management from rest of you application ² using extractor ´ Create instances of Thread « « Extend the thread class and override its run() method Implement a ¶Runnable· object 14 . Two basic strategies for concurrent application « To directly control thread creation and management ² Instantiate the thread when needed .

println("Hello from a thread!"). } public void run(Strings arg[]) { } public static void main(String args[]) { // just started a thread (new Thread( new HelloRunnable() ) ). // We need to get a thread for the runnable created Thread THR1 = new Thread(HR1).start(). } } 15 .CREATING RUNNABLE OBJECTS public class HelloRunnable implements Runnable { @Override public void run() { System.out. // Create a Runnable instance HelloRunnable HR1 = new HelloRunnable().

HelloThread HT = new HelloThread().printStackTrace(). public void run() { System.out. HT.EXTENDING THE THREAD public class HelloThread extends Thread { static int j =0. try { HT.sleep(3999L). } public static void main(String args[]) { (new HelloThread() ). } } } Your Output: Hello from a thread #0! Hello from a thread #1! 16 .start().println("Hello from a thread #µ+j+++µ!"). } catch (InterruptedException e) { e.start().

thus.suspend is inherently deadlock-prone. Unlike other unchecked exceptions. The corruption can manifest itself at any time after the actual damage occurs. MIN_PRIORITY = 1 When threads operate on damaged objects. int nano ) Yield Suspend/resume IsAlive() Join() Because it is inherently unsafe.THREAD CONTROL METHODS METHOD Name setName(String ThreadName) getName setPriority(int newPriority) Method Desc Assign a Name for Thread STOP ± Why we should not use it Notes getPriority() currentThread() start() stop()/ stop(throwable t)/ stop1() run() Sleep(long millis). even hours or days in the future. or it may be pronounced.) If any of the objects previously protected by these Change priority of thread Java rangemonitors were in an inconsistent state. other threads may now view these objects in an inconsistent state. Check if thread is alive 17 . no thread can access this resource until the target thread is Willingly allow thread to give up processor resumed. If the target thread holds a lock on the monitor protecting a critical system resource when it is suspended. Get current thread reference ThreadDeath kills threads silently. Subclasses will override this method SUSPEND/RESUME are deprecated Your program specific code goes here Sleep in period of millis Thread. Sleep(long millis. arbitrary behavior can result. (The monitors are unlocked as the ThreadDeath exception propagates up Retrieve the name of Thread the stack. the user has no warning that his program may be corrupted. Such deadlocks typically manifest themselves as "frozen" processes. If the thread that would resume the target thread attempts to lock this monitor prior to calling Allow thread to pause and restart resume. deadlock results. This behavior may be subtle and difficult Read current priority to detect. Stopping a thread causes it to unlock all the monitors that it has locked. Such objects MAX_PRIORITY = 10 are said to be damaged.

´ We have to use try{«.}catch{«} blocks 18 .THREADS SLEEP TOO! ´ The static method 'sleep(<long> <param1>)¶ « « Makes the current thread stop execution for an amount of time The unit of time is milliseconds (ms = 1/1000 of a sec) ´ A checked exception called 'InterruptedException' « « is thrown by the sleep() method if another process attempts to interrupt the thread before the specified time-interval is over. This Exception should be handled when the sleep method is used.

// Create a Runnable instance HelloRunnable HR1 = new HelloRunnable().out. } catch(InterruptedException e) { System.SLEEPING THREADS public class HelloRunnable implements Runnable { @Override public void run() { System.start(). } } public void run(Strings arg[]) { } public static void main(String args[]) { // just started a thread (new Thread( new HelloRunnable() ) ).µ).sleep(1000L). try { Thread.out.println(´Terminated prematurely due to Exception. // We need to get a thread for the runnable created Thread THR1 = new Thread(HR1).println("Hello from a thread!"). } } 19 .

isAlive()).println("Thread Three is alive: " + ob3. System.println(name + " exiting. Three: 2 public void run() { ob1.t.t. Three exiting.out.out. System. System. System."). Two: 4 } System. } } Thread One is alive: false Thread Two is alive: false Thread Three is alive: false Main thread exiting.out. One: 5 MyThread ob3 = new MyThread("Three"). i > 0.isAlive()).out. Thread. name).out. System.out.println("Thread Three is alive: " + ob3.isAlive()).out.join().println("Thread One is alive: " + ob1. MyThread ob2 = new MyThread("Two").out.t. t = new Thread(this.out.println(name + ": " + i).println("Thread Two is alive: " + ob2. } catch (InterruptedException e) { One exiting. i--) { ob3.join(). Three: 4 System.println("Thread Two is alive: " + ob2.").join().t. try { ob2.out. System. Two exiting.THREAD JOIN() Thread One is alive: true class MyThread implements Runnable { Thread Two is alive: true ´ public class MainClass { String name.out. Two: 3 System. One: 1 for (int i = 5. } } } catch (InterruptedException e) { Two: 5 System. Waiting for threads to finish.start().out.t. Three: 1 System. Two: 2 } Two: 1 } System.out.println("Main thread Interrupted"). // name of thread public static void main(String args[]) { Thread Three is alive: true MyThread ob1 = new MyThread("One").isAlive()).println("Waiting for threads to finish.println("Main thread exiting. Three: 3 } try { One: 2 System."). 3 One: t.isAlive()).println(name + " interrupted.sleep(1000).t.isAlive()).t.t.println("New thread: " + t). Thread t. 20 .println("Thread One is alive: " + ob1. Three: 5 MyThread(String threadname) { One: 4 name = threadname.t.").

SYNCHRONIZATION ´ Many threads share a common object or data « « Usually many reads and few writes Lead to spurious situation ² One of the thread is updating and another is reading ´ Java way « « Give the thread an exclusive access to manipulate data .Semaphore Other threads wait Only one object will be able to lock at one time Every object has a monitor and a monitor lock ´ Monitor ² a Java built-in for synchronization « « ´ You need a Synchronization block 21 .

SYNCHRONIZATION .MONITOR ´ Mutual Exclusion « Associated with one or block lines of codes ² ² The lines of codes must be executed in that order and not interruptible The corresponding thread acquires the lock « All other threads will wait and serviced in the order ´ Co-operation « « « Desirable when one thread is responsible for updating while another thread needs updated data Thread(s) needing updated data will request wait() request and thread remains in wait state Thread updating data will issue ´Notifyµ or ´Notify Allµ and releases monitor 22 .

displayState( "Producer writes " + buffer ). place thread in waiting state buffer = value. // tell waiting thread(s) to enter runnable state 23 . displayState( "Producer writes " + buffer ). if we are synchronizing in that objects. place thread in waiting state Synchronized(this) public synchronized void set( int value ) throws InteruptException { // place value into buffer // while there are no empty locations.SYNCHRONIZATION ´ format Synchronized Blocks or statements synchronized ( object ) { ´ Synchronized Methods synchronized <return type> SomeMethod(<arguments if any>) { // Method body } statements } // end synchronized statement Typically your object will be the this operator. notifyAll(). // tell waiting thread(s) to enter runnable state } } } // indicate producer cannot store another value // until consumer retrieves current buffer value occupied = true. // set new buffer value // indicate producer cannot store another value // until consumer retrieves current buffer value occupied = true. // set new buffer value { buffer = value. notifyAll(). public void set( int value ) throws InterruptException { // place value into buffer // while there are no empty locations.

} catch (InterruptedException e) {} } drop.format("MESSAGE RECEIVED: %s%n". "Does eat oats". try { Thread.take(). public Producer(Drop drop) { this. Random random = new Random().nextInt(5000)). } public void run() { Random random = new Random(). try { Thread. public Consumer(Drop drop) { this. for (int i = 0.out.drop = drop.put("DONE").put(importantInfo[i]). } catch (InterruptedException e) {} } } } 24 . message = drop.INTER-THREAD COMMUNICATIONS public class Producer implements Runnable { private Drop drop. for (String message = drop. } } public class Consumer implements Runnable { private Drop drop. !message.length.drop = drop. "Little lambs eat ivy". message). i < importantInfo.equals("DONE").sleep(random. i++) \ { drop.nextInt(5000)). } public void run() { String importantInfo[] = { "Mares eat oats". "A kid will eat ivy too´ }.sleep(random.take() ) { System.

//Notify consumer that status has changed. } catch (InterruptedException e) {} } //Toggle status. //Store message. } } 25 . } } public class ProducerConsumerExample { public static void main(String[] args) { Drop drop = new Drop(). while (empty) { try { wait(). //Notify producer that status has changed. } catch (InterruptedException e) {} } //Toggle status. empty = true. empty = false. while (!empty) { try { wait(). (new Thread(new Consumer(drop))).message = message.INTER-THREAD COMMUNICATIONS (CONTD) public class Drop { //Message sent from producer to consumer. //True if consumer should wait for producer to send message. false //if producer should wait for consumer to retrieve message.start().start(). return message. this. public synchronized String take() { //Wait until message is available. private boolean empty = true. (new Thread(new Producer(drop))). } public synchronized void put(String message) { //Wait until message has been retrieved. private String message. notifyAll(). notifyAll().

so the actions that would enable each thread to continue execution can never occur.DEADLOCK ± WHAT IS IT? When a waiting thread (let us call this thread1) cannot proceed because it is waiting (either directly or indirectly) for another thread (let us call this thread2) to proceed. while simultaneously thread2 cannot proceed because it is waiting (either directly or indirectly) for thread1 to proceed. ´ The two threads are waiting for each other. ´ 26 .






´ 32 . ´ Best known way of resolving the deadlock is resource ordering or restructuring the programming logic.DEADLOCK ± HOW TO RESOLVE? There is no best solution.

and thread states ² new.runnable and thread extends. a third kind extractors Threads can wait while the remaining program can continue to execute Threads can wait for another thread to complete using the ¶join· method Use of synchronization for blocks of code or a method to allow us to manipulate data and preventing blocking. terminated Creating Threads . We can perform inter-thread communication using a shared code and synchronization Deadlocks can still occur when two threads are waiting for an object to be released by the other thread ( could be directly or indirectly) ´ ´ 33 . timed wait. runnable.C0NCLUSION ´ ´ ´ ´ ´ ´ ´ ´ Multitasking and Processes Thread allow parallelization in our programming activity and logics. blocked. Thread do not require new memory and hence termed Lightweight Lifecycle of a Thread. wait.


You're Reading a Free Preview

/*********** DO NOT ALTER ANYTHING BELOW THIS LINE ! ************/ var s_code=s.t();if(s_code)document.write(s_code)//-->