1 / 23

Understanding Multithreading in Java: A Programmer's Guide

Learn about the fundamentals of multithreading in Java, the concept of multitasking, thread scheduling, priority scheduling, thread states, and life cycle in applets. Discover how to create multithreaded programs, handle thread priorities, and use methods like sleep(), yield(), and join(). Explore multithreading best practices and practical examples. This guide provides insights into how to optimize CPU time with multithreading and design efficient Java applications.

hbellamy
Download Presentation

Understanding Multithreading in Java: A Programmer's Guide

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. Threads Fall 2005 IST 311

  2. Threads • A thread is a single sequence of executable statements within a program • Java applications, flow begins with first statement in main( ) • Java applets, flow control begins with first statement in init( ) • CPU executes one instruction at a time • Multiple threads executing concurrently and rapidly gives the appears that the CPU is running more than one task at a time

  3. Threads • Multitasking – technique of concurrently executing several tasks within a program • Downloading an image from the internet while running a speadsheet calculation • Multitasking requires use of separate thread for each task

  4. Threads • CPU uses fetch-execute cycle to retrieve next instruction from memory and execute it • Multithreaded programs make it possible to divide up the CPU’s time and share it among the threads • CPU’s schedule is managed by a scheduling algorithm • Controlled by the operating system and JVM

  5. Threads • Thread scheduling is handled differently on Unix, Windows, and Macintosh systems • One common scheduling technique is known as time slicing • Each thread alternatively gets a slice of CPU time • System gives each thread a quantum of CPU time to execute instructions • When quantum expires, thread would be preempted and another thread given a chance to run • On a 300-megahertz CPU, a thread could execute 300,000 machine instructions during a millisecond

  6. Threads • Priority scheduling – higher priority threads are allowed to run to completion before lower-priority threads • High-priority thread might be keyboard input from the user so the user doesn’t experience noticeable delays

  7. Threads

  8. Threads • How to create a multithreaded program: • Implement the Runnable interface for an existing class by implementing the void run( ) method • Create several Thread instances by first creating instances of the Runnable class and passing each as an argument to the Thread( ) constructor • For each thread instance, start it by invoking the start( ) method on it.

  9. Threads • NumberPrinter and Number program

  10. Threads • start( ) and stop( ) methods used to control thread’s execution • Sometimes called automatically • An applet is treated as a thread by a browser, which is responsible for starting and stopping it • setPriority( int) lets you set a thread’s priority setPriority(Thread.MAX_PRIORITY);

  11. Threads • Thread implementation in Java is platform dependent • Test to ensure program will perform correctly on a given platform • Coordinate behavior of 2 threads by giving one a higher priority • High-priority thread that never gives up CPU time can starve lower-priority threads

  12. Threads • Thread.sleep( ) method causes the thread to yield and not be scheduled until a certain amount of real time has passed • Halt a running thread for a given number of milliseconds • Throws an InterruptedException which is a checked exception • sleep( ) must be embedded within a try/ catch block or the method it is in must throw an InterruptedException

  13. Threads • Thread.yield( ) method causes the thread to yield CPU, allowing the thread scheduler to choose another thread

  14. Threads • Threads are asynchronous • The order of execution is sporadic and unpredictable from programmer’s point of view • Impossible for a programmer to predict when and for how long an individual thread will run

  15. Thread States and Life Cycle

  16. Part 2

  17. Applets • start( ) is called once when the applet is started. • Calls init( ) and paint( ) automatically and then calls run( ) to run the applet • run( ) starts the applet running. • Called by start( ) • stop( ) is called by the browser or appletviewer when the applet is quit

  18. Applets • init( ) is called automatically when the applet starts to perform initializations • paint( ) paints the graphics on the applet. Called once at start and then can be called by repaint( ) when applet’s appearance is changed.

  19. Calendar • The class Calendar contains methods and constants to represent the date and time • Found in java.util.* • Constructors in Calendar are protected, so you must use getInstance( ) method to return an instance of a Calendar subclass • May retrieve hour, minutes, seconds: int hours = time.get(Calendar.HOUR); int mins = time.get(Calendar.MINUTE); int secs = time.get(Calendar.SECOND);

  20. Threads • Applet to run a clock

  21. Threads • We override methods init( ),start( ), and stop( ) • Web browser or appletviewer invokes these overridden methods • Applet responds to controlling program • With program like Clock, browser or viewer cannot regain control – stuck in an infinite loop

  22. Threads • Java is an implicitly threaded language • Several threads are started automatically every time you run a Java applet or application • For example, a separate thread will start for each • Events generated by users (pressing buttons in a GUI) • Automatic garbage collection • Creation of a programmer’s own threads for running sections of a program independently

  23. Threads • To solve the Clock problem, we need to allow the applet to run in parallel with the browser • Give it a thread of its own • Will react to the mouse button • Get into the habit of running an applet in its own thread

More Related