Wednesday 2 March 2016

Threads

All the changes we’ve made in HelloJava4 have to do with setting up a separate thread of execution to make the text blink. Java is a multithreaded language, which means there can be many paths of execution effectively running at the same time. A thread is a separate flow of control within a program. Conceptually, threads are similar to processes. Unlike processes, multiple threads share the same program space, which means that they can share variables and methods (but also have their own local variables). Threads are also quite lightweight in comparison to processes, so it’s conceivable for a single application to be running many (perhaps hundreds or thousands) of threads concurrently. Multithreading provides a way for an application to handle many different tasks at the same time. It’s easy to imagine multiple things going on at the same time in an application like a web browser. The user could be listening to an audio clip while scrolling an image; at the same time, the browser can be downloading another image. Multithreading is especially useful in GUI-based applications because it improves the interactive performance of these applications. Unfortunately for us, programming with multiple threads can be quite a headache. The difficulty lies in making sure routines are implemented so they can be run concurrently by more than one thread at a time. If a routine changes the value of multiple state variables, for example, it may be important that those changes happen together, without overlapping changes affecting each other. Later in this section, we’ll examine briefly the issue of coordinating multiple threads’ access to shared data. In other languages, synchronization of threads can be extremely complex and error-prone. You’ll see that Java gives you powerful tools that help you deal with many of these problems. We will have a detailed discussion of threads. The Java runtime system creates and manages a number of threads. (Exactly how varies with the implementation.) We’ve already mentioned the repaint thread, which manages repaint() requests and event processing for GUI components that belong to the java.awt and javax.swing packages. Our example applications have done most of their work in one thread. Methods such as mouseDragged() and actionPerformed() are invoked by the windowing thread and run by its thread, on its time. Similarly, our HelloComponent constructor runs as part of the main application thread (the main() method). This means we are somewhat limited in the amount of processing we do within these methods. If we were, for instance, to go into an endless loop in our constructor, our application would never appear because it would never finish initializing. If we want an application to perform any extensive processing, such as animation, a lengthy calculation, or communication, we should create separate threads for these tasks.

0 comments:

Post a Comment