호빗의 인간세상 탐험기

What are threads? 본문

IT이야기

What are threads?

딜레이라마 2017. 2. 8. 21:20
반응형

What are threads? Nearly every operating system supports the concept of processes -- independently running programs that are isolated from each other to some degree. Threading is a facility to allow multiple activities to coexist within a single process. Most modern operating systems support threads, and the concept of threads has been around in various forms for many years. Java is the first mainstream programming language to explicitly include threading within the language itself, rather than treating threading as a facility of the underlying operating system. Threads are sometimes referred to as lightweight processes. Like processes, threads are independent, concurrent paths of execution through a program, and each thread has its own stack, its own program counter, and its own local variables. However, threads within a process are less insulated from each other than separate processes are. They share memory, file handles, and other per-process state. A process can support multiple threads, which appear to execute simultaneously and asynchronously to each other. Multiple threads within a process share the same memory address space, which means they have access to the same variables and objects, and they allocate objects from the same heap. While this makes it easy for threads to share information with each other, you must take care to ensure that they do not interfere with other threads in the same process. The Java thread facility and API is deceptively simple. However, writing complex programs that use threading effectively is not quite as simple. Because multiple threads coexist in the same memory space and share the same variables, you must take care to ensure that your threads don't interfere with each other. 

Every Java program uses threads 

Every Java program has at least one thread -- the main thread. When a Java program starts, the JVM creates the main thread and calls the program's main() method within that thread. The JVM also creates other threads that are mostly invisible to you -- for example, threads associated with garbage collection, object finalization, and other JVM housekeeping tasks. Other facilities create threads too, such as the AWT (Abstract Windowing Toolkit) or Swing UI toolkits, servlet containers, application servers, and RMI (Remote Method Invocation). 


Why use threads? 

There are many reasons to use threads in your Java programs. If you use Swing, servlets, RMI, or Enterprise JavaBeans (EJB) technology, you may already be using threads without realizing it. Some of the reasons for using threads are that they can help to:

• Make the UI more responsive 

• Take advantage of multiprocessor systems 

• Simplify modeling 

• Perform asynchronous or background processing


More responsive UI

Event-driven UI toolkits, such as AWT and Swing, have an event thread that processes UI events such as keystrokes and mouse clicks. AWT and Swing programs attach event listeners to UI objects. These listeners are notified when a specific event occurs, such as a button being clicked. Event listeners are called from within the AWT event thread. If an event listener were to perform a lengthy task, such as checking spelling in a large document, the event thread would be busy running the spelling checker, and thus would not be able to process additional UI events until the event listener completed. This would make the program appear to freeze, which is disconcerting to the user. To avoid stalling the UI, the event listener should hand off long tasks to another thread so that the AWT thread can continue processing UI events (including requests to cancel the long-running task being performed) while the task is in progress. 

Take advantage of multiprocessor systems 

Multiprocessor (MP) systems are much more common than they used to be. Once they were found only in large data centers and scientific computing facilities. Now many low-end server systems -- and even some desktop systems -- have multiple processors. Modern operating systems, including Linux, Solaris, and Windows NT/2000, can take advantage of multiple processors and schedule threads to execute on any available processor. The basic unit of scheduling is generally the thread; if a program has only one active thread, it can only run on one processor at a time. If a program has multiple active threads, then multiple threads may be scheduled at once. In a well-designed program, using multiple threads can improve program throughput and performance. 

Simplicity of modeling 

In some cases, using threads can make your programs simpler to write and maintain. Consider a simulation application, where you simulate the interaction between multiple entities. Giving each entity its own thread can greatly simplify many simulation and modeling applications. Another example where it is convenient to use separate threads to simplify a program is when an application has multiple independent event-driven components. for example, an application might have a component that counts down the number of seconds since some ibm.com/developerWorks Presented by developerWorks, your source for great tutorials Page 4 of 30 Introduction to Java threads event and updates a display on the screen. Rather than having a main loop check the time periodically and update the display, it is much simpler -- and less error-prone -- to have a thread that does nothing but sleep until a certain amount of time has elapsed and then update the on-screen counter. This way the main thread doesn't need to worry about the timer at all.


Asynchronous or background processing

 Server applications get their input from remote sources, such as sockets. When you read from a socket, if there is no data currently available, the call to SocketInputStream.read() will block until data is available. If a single-threaded program were to read from the socket, and the entity on the other end of the socket were never to send any data, the program would simply wait forever, and no other processing would get done. On the other hand, the program could poll the socket to see if data was available, but this is often undesirable for performance reasons. If, instead, you created a thread to read from the socket, the main thread could perform other tasks while the other thread waited for input from the socket. You can even create multiple threads so you can read from multiple sockets at once. In this way, you are notified quickly when data is available (because the waiting thread is awakened) without having to poll frequently to check if data is available. The code to wait on a socket using threads is also much simpler and less error-prone than polling would be.

Simple, but sometimes risky

While the Java thread facility is very easy to use, there are several risks you should try to avoid when you create multithreaded programs. When multiple threads access the same data item, such as a static field, an instance field of a globally accessible object, or a shared collection, you need to make sure that they coordinate their access to the data so that both see a consistent view of the data and neither steps on the other's changes. The Java language provides two keywords for this purpose: synchronized and volatile. We will explore the use and meaning of these keywords later in this tutorial. When accessing variables from more than one thread, you must ensure that the access is properly synchronized. For simple variables, it may be enough to declare the variable volatile, but in most situations, you will need to use synchronization. If you are going to use synchronization to protect access to shared variables, you must make sure to use it everywhere in your program where the variable is accessed.

Don't overdo it 

While threads can greatly simplify many types of applications, overuse of threads can be hazardous to your program's performance and its maintainability. Threads consume resources. Therefore, there is a limit on how many threads you can create without degrading Presented by developerWorks, your source for great tutorials ibm.com/developerWorks Introduction to Java threads Page 5 of 30 performance. In particular, using multiple threads will not make a CPU-bound program run any faster on a single-processor system.


Example: Using a thread for timing and a thread to do work

The following example uses two threads, one for timing and one to do actual work. The main thread calculates prime numbers using a very straightforward algorithm. Before it starts, it creates and starts a timer thread, which will sleep for ten seconds, and then set a flag that the main thread will check. After ten seconds, the main thread will stop. Note that the shared flag is declared volatile.


/**

* CalculatePrimes -- calculate as many primes as we can in ten seconds

*/

public class CalculatePrimes extends Thread {

public static final int MAX_PRIMES = 1000000;

public static final int TEN_SECONDS = 10000;

public volatile boolean finished = false;

public void run() {

int[] primes = new int[MAX_PRIMES];

int count = 0;

for (int i=2; count<MAX_PRIMES; i++) {

// Check to see if the timer has expired

if (finished) {

break;

}

boolean prime = true;

for (int j=0; j<count; j++) {

if (i % primes[j] == 0) {

prime = false;

break;

}

}

if (prime) {

primes[count++] = i;

System.out.println("Found prime: " + i);

}

}

}




반응형

'IT이야기' 카테고리의 다른 글

JAVA MultiThread DegienPattern2  (0) 2017.02.17
JAVA MultiThread DegienPattern  (0) 2017.02.17
JAVA MultiThread2  (0) 2017.02.08
JAVA MultiThread  (0) 2017.02.08
네트워크 보안  (0) 2017.02.06
Comments