before we begin
play

Before we begin Next Monday: Exam 1 Threads Thursday: Review - PDF document

Before we begin Next Monday: Exam 1 Threads Thursday: Review session Send questions via e-mail. Introduction Any questions? Plan Threads Today: Introduction to threads Remember this from CS2? Tomorrow:


  1. Before we begin • Next Monday: Exam 1 Threads – Thursday: Review session – Send questions via e-mail. Introduction • Any questions? Plan Threads • Today: Introduction to threads • Remember this from CS2? • Tomorrow: Scheduling / Synchronization – Demo • Thursday: Review • Next Monday: Exam • Next Tuesday: more Synchronization • Next Thursday: Examples Thread Thread • A thread is a single sequential flow of • A thread is not a program control within a program – It cannot run on its own – Runs within a program • Sometimes called: – Execution context – Lightweight process

  2. Thread Java and Threads • Multiple threads can be running at the same • When a Java Virtual Machine starts up, time within a single program there is usually a single thread (which typically calls the method named main of some designated class). • Other threads are created behind the scenes (e.g. GUI) Understanding Threads Thread Objects • As is everything else, threads in Java are • You must be able to answer the following represented as objects. questions • The code that a thread executes is contained – What code does a thread execute? in its run() method. – What states can a thread be in? – There is nothing special about run, anyone can – How does a thread change its state? call it. – How does synchronization work? • To make a thread eligible for running you call its start() method Example Interface Runnable public class CounterThread extends Thread { • At times, it may be inconvenient to use public void run() { inheritance in creating a Thread for ( int i=0; i<10; i++) System.out.println(“Count: “ + i); – Example: Clock Applet } public static void main(String args[]) { CounterThread ct = new CounterThread(); • Recall, Java does not support multiple ct.start(); inheritance } } – But it does support interfaces

  3. Interface Runnable Example public class DownCounter implements Runnable { public void run() { for (int i=10; i>0; i--) • Classes that implement Runnable can System.out.println(“Down: “+ i); } also be run as separate threads public static void main(String args[]) { • Runnable classes have a run() method DownCounter ct = new DownCounter(); Thread t = new Thread(ct); • In this case you create a thread specifying the Runnable object as the constructor t.start(); } argument } Life of a thread isAlive() • A thread will be considered “live” as long • The method isAlive() determines if a as its run method has not completed thread is considered to be alive • Note that calling start() may not result – A thread is alive if it has been started and has in an immediate call to run(). not yet died. • Once a thread’s run() has completed, it is • This method can be used to determine if a considered “dead”. thread has actually been started and has not • You cannot restart a dead thread, but you yet terminated can access its state and behavior. Daemons Daemon Threads • The Greek mythology definition: • Daemon threads never die. – Demon, n, A spirit, or immaterial being, – The run() method will never return. holding a middle place between man and dieties • Can set a Thread to be a daemon using the • The OS definition: Thread’s setDaemon() method – A program that is not invoked explicitly, but lies dormant waiting for some condition to occur – Rationalized as acronym for: Disk And Execution MONitor

  4. When Execution Ends Multiple Threads • The Java Virtual Machine continues to execute • The real challenge / advantage of threads is threads until either of the following occurs: the ability to run multiple threads – The exit method of class Runtime has been called simutaneously. – All threads that are not daemon threads have died, either by returning from the call to the run() or by throwing an exception that propagates beyond run() . • Questions? Many Many public class Many extends Thread { • The use of multiple threads makes the private int retry; private String info; programs written non-deterministic public Many (int retry, String info) { this.retry = retry; this.info = info; } – The order in which the threads will do their public void run () { work cannot be assumed. for (int n = 0; n < retry; ++ n) work(); quit(); } protected void work () { System.out.print(info); } protected void quit () { System.out.print('\n'); } public static void main (String args []) { if (args != null) for (int n = 0; n < args.length; ++n) new Many(args.length, args[n]).start(); }} Many Java Threads java Many one two three • Questions so far? onethreetwo or twothreeone

  5. Threads scheduling Thread Scheduling • Although the JVM can conceptually run • Threads are scheduled like processes multiple threads simultaneously • Thread states – Running – Most machines have only 1 processor – Waiting, Sleeping, Suspended, Blocked – The JVM must timeshare – Ready – This process is performed by the JVM – Dead scheduler. • When you invoke start() the Thread is marked ready and placed in the thread queue Thread States Thread schedulers The start() method places a thread in the ready state • Types Ready The scheduler selects a thread and places it in the running state – Non-preemptive – Once a thread has the processor (Running), it keeps it until it is done – Pre-emptive – Scheduler may interrupt the work of a Waiting Running thread, placing it back in the Ready state. • Most Java implementations use preemptive scheduling. A thread that is waiting for I/O, was suspended, is sleeping, – the type of scheduler will depend on the JVM that you blocked, or otherwise is unable to do any more work is placed in the waiting state use. Thread Priorities Thread Priorities • Threads can have priorities from 1 to 10 (10 is the • Higher priority threads should get first dibs highest) on the processor • The default priority is 5 • Higher priority thread can kick a lower – The constants Thread.MAX_PRIORITY, priority thread off the processor. Thread.MIN_PRIORITY, and • Starvation (indefinite blocking) Thread.NORM_PRORITY give the actual values • Priorities can be changed via setPriority() – Lower priority thread may wait indefinitely for (there is also a getPriority()) the processor.

  6. Thread Priorities Timing • In Java, priorities are a hint to the scheduler and • In general, you should never assume any not a mandate. ordering of thread execution. • From the Java spec: When there is a competition for processing resources, • As we’ll see, proper timing in threads with higher priority are generally executed in preference to threads with lower priority. Such multithreading programming is of utmost preference is not, however, a guarantee that the higher importance… priority thread will always be running Take home message: • Questions? – Never assume that the scheduler will execute threads in priority order. Summary Next time • Threads • Thread methods dealing with scheduling – What they are • More thread examples. – The Thread object • Thread vs. Runnable – Life of a Thread • Questions? – Thread States / Scheduling – Priorities

Recommend


More recommend