Presentation is loading. Please wait.

Presentation is loading. Please wait.

Java Threads. What is a Thread? A thread can be loosely defined as a separate stream of execution that takes place simultaneously with and independently.

Similar presentations


Presentation on theme: "Java Threads. What is a Thread? A thread can be loosely defined as a separate stream of execution that takes place simultaneously with and independently."— Presentation transcript:

1 Java Threads

2 What is a Thread? A thread can be loosely defined as a separate stream of execution that takes place simultaneously with and independently of everything else that might be happening. A thread is like a classic program that starts at point A and executes until it reaches point B A thread runs independently of anything else happening in the computer. Without threads an entire program can be held up by one CPU intensive task or one infinite loop, intentional or otherwise. With threads the other tasks that don't get stuck in the loop can continue processing without waiting for the stuck task to finish.

3 It turns out that implementing threading is harder than implementing multitasking in an operating system. The reason it's relatively easy to implement multitasking is that individual programs are isolated from each other. Individual threads, however, are not.

4 Threaded environments like Java allow a thread to put locks on shared resources so that while one thread is using data no other thread can touch that data. This is done with synchronization. Synchronization should be used sparingly since the purpose of threading is defeated if the entire system gets stopped waiting for a lock to be released. The proper choice of objects and methods to synchronize is one of the more difficult things to learn about threaded programming.

5 How Java Uses Threads Java applications and applets are naturally threaded. The runtime environment starts execution of the program with the main() method in one thread. Garbage collection takes place in another thread. Screen updating occurs in a third thread. There may be other threads running as well, mostly related to the behavior of the applet viewer or web browser. All of this happens invisibly to the programmer.

6 When to thread The simplest reason for adding a separate thread is to perform a long calculation. – For instance if you're trying to find the ten millionth prime number, you probably don't want to make users twiddle their thumbs while you search. Or you may be waiting for a resource that isn't available yet, a large graphic to download from the Internet, for example. –Once again you shouldn't make the user wait while your program waits. Any operation that is going to take a noticeable period of time should be placed in its own thread.

7 The other reason to use threading is to more evenly divide the computer's power among different tasks. If you want to draw random rectangles on the display, you would still like the applet to respond to user input. –If all the CPU time is spent drawing rectangles, there's nothing left over for the user. On a preemptively multitasking operating system like Solaris or Windows NT, the user may at least be able to kill the application. On a cooperatively multitasking operating system like the MacOS or Windows, the user may have to reboot their machine. This is a bad thing. With threads you can set the priority of different processes, so that user input receives a high priority and drawing pretty pictures receives a low priority. Then the user can stop the applet without flipping the power switch on their machine.

8 The Thread Classes The Thread class has three primary methods that are used to control a thread: public void start() –The start() method prepares a thread to be run; public void run() –the run() method actually performs the work of the thread; public final void stop() –the stop() method halts the thread. The thread dies when the the run() method terminates or when the thread's stop() method is invoked.

9 You never call run() explicitly. – It is called automatically by the runtime as necessary once you've called start(). There are also methods to supend and resume threads, to put threads to sleep and wake them up, to yield control to other threads, and many more.

10 Runnable Interface The Runnable interface allows you to add threading to a class which, for one reason or another, cannot conveniently extend Thread. It declares a single method, run(): public abstract void run() By passing an object which implements Runnable to a Thread() constructor, you can substitute the Runnable's run() method for the Thread's own run() method. (More properly the Thread object's run() method simply calls the Runnable's run() method.)

11 To use threads efficiently and without errors you must understand various aspects of threads and the Java runtime system. You need to know how to provide a body for a thread, the life cycle of a thread, how the runtime system schedules threads, thread groups, and what daemon threads are and how to write them.

12 Threads Three fields –Max_Priority –Min_Priority –Normal_Priority

13 Static Thread methods Thread th = Thread.currentThread(); –gets the Thread object for the thread that executes this call (the "current thread"). Thread.sleep(milliseconds); –puts the current thread to sleep for that length of time. (almost always called in a try block to catch the InterruptedException.) Thread.yield(); –lets another thread run (if there is one that can run).

14 normal Thread methods void start() –starts the thread running. The run() method of the Runnable attached to the Thread is called in that thread. void stop() –stops the thread immediately. The thread cannot be restarted. void suspend() –stops the thread from running, until a resume() is called.

15 void resume() –causes the thread to continue running from where it was suspended. void setPriority(int prio) –changes the priority of the thread. Threads with a higher valued priority run preferentially to lower priority threads. int getPriority() –returns the priority of the thread. void join() causes the current thread to wait until this thread is finished (either run() returns or the thread is stop()-ed).

16 Daemon Threads User Threads Daemon Threads –When a Java Virtual Machine starts up, there is usually a single non-daemon thread (which typically calls the method named main of some designated class). The Java Virtual Machine continues to execute threads until either of the following occurs: The exit method of class Runtime has been called and the security manager has permitted the exit operation to take place. All threads that are not daemon threads have died, either by returning from the call to the run method or by throwing an exception that propagates beyond the run method.


Download ppt "Java Threads. What is a Thread? A thread can be loosely defined as a separate stream of execution that takes place simultaneously with and independently."

Similar presentations


Ads by Google