Home > Java > javaTutorial > body text

What is the use of java threads

(*-*)浩
Release: 2019-05-27 17:28:55
Original
4200 people have browsed it

This tutorial examines the basics of threads - what they are, why they are useful, and how to get started writing simple programs that use threads. (Recommended course: Java Video Tutorial)

What is a thread?

Almost every operating system supports the concept of processes - programs that are somewhat isolated from each other and run independently.

Threading is a tool that allows multiple activities to coexist in a process. Most modern operating systems support threads, and the concept of threads has been around in various forms for many years. Java was the first major programming language to explicitly include threads in the language itself; it did not treat threading as a tool of the underlying operating system.

Sometimes, threads are also called lightweight processes. Just like processes, threads are independent, concurrent execution paths in the program. Each thread has its own stack, its own program counter, and its own local variables. However, threads within a process are less isolated from each other than separate processes. They share memory, file handles, and other state that each process should have.

A process can support multiple threads, which appear to execute simultaneously but are not synchronized with each other. Multiple threads in a process share the same memory address space, which means they can access the same variables and objects, and they allocate objects from the same heap. Although this makes it easier to share information between threads, you must be careful to ensure that they do not interfere with other threads in the same process.

Java threading tools and API are deceptively simple. However, writing complex programs that use threads efficiently is not very easy. Because there are multiple threads coexisting in the same memory space and sharing the same variables, you must be careful to ensure that your threads do not 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 in this thread.

The JVM also creates other threads that you generally don't see -- for example, threads related to garbage collection, object termination, and other JVM housekeeping tasks. Other tools also create threads, such as AWT (Abstract Windowing Toolkit) or Swing UI Toolkit, servlet containers, application servers, and RMI (Remote Method Invocation).

Why use threads?

There are many reasons to use threads in Java programs. If you use Swing, servlet, RMI, or Enterprise JavaBeans (EJB) technology, you may not realize that you are already using threads.

Some reasons to use threads are that they can help:

Make the UI more responsive

Take advantage of multi-processor 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 handles UI events such as keystrokes or mouse clicks.

AWT and Swing programs connect event listeners to UI objects. These listeners are notified when a specific event occurs (such as a button being clicked). Event listeners are called in the AWT event thread.

If the event listener performs a long-lasting task, such as checking spelling in a large document, the event thread will be busy running the spell checker, so no additional processing can be done before the event listener is completed. UI events. This can make the program appear to be stuck, leaving the user confused.

To avoid delayed UI response, the event listener should put longer tasks into another thread, so that the AWT thread can continue to process UI events (including canceling the execution of the task) during the execution of the task. requests for long-running tasks).

Utilizing multi-processor systems

Multi-processor (MP) systems are more common than in the past. Previously they could only be found in large data centers and scientific computing facilities. Many low-end server systems today - 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 usually a 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, multiple threads can be scheduled simultaneously. In a well-designed program, using multiple threads can improve program throughput and performance.

Simplified Modeling

In some cases, using threads can make programs simpler to write and maintain. Consider a simulation application in which you want to simulate interactions between multiple entities. Giving each entity its own thread can greatly simplify many simulations and modeling applications.

Another example where using 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 seconds after an event and updates the screen display. Rather than having a main loop that periodically checks the time and updates the display, it's simpler and less error-prone to have a thread do nothing and sleep until a certain amount of time later, when the on-screen counter is updated. This way, the main thread doesn't need to worry about the timer at all.

Asynchronous or background processing

A server application gets input from a remote source such as a socket. When reading from a socket, if no data is currently available, the call to SocketInputStream.read() will block until data is available.

If a single-threaded program wants to read the socket, and the entity on the other end of the socket does not send any data, then the program will just wait forever without performing other processing. Instead, a program can poll the socket to see if data is available, but this is generally not used because of the performance impact.

However, if you create a thread to read from the socket, then while this thread is waiting for input from the socket, the main thread can perform other tasks. You can even create multiple threads so you can read from multiple sockets at the same time. This way you'll be notified quickly when data is available (as the waiting thread is woken up) without having to poll frequently to check if data is available. Code that uses threads to wait on sockets is also simpler and less error-prone than polling.

Simple, but sometimes risky

While the Java threading tools are very easy to use, there are some risks that you should try to avoid when you create multi-threaded 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 ensure that they coordinate their access to the data so that they can all see the data. Consistent views without interfering with each other's changes. To achieve this purpose, the Java language provides two keywords: synchronized and volatile. We will look at the purpose and meaning of these keywords later in this tutorial.

When accessing variables from multiple threads, you must ensure that the access is correctly synchronized. For simple variables, declaring the variable volatile may be sufficient, but in most cases, synchronization is required.

If you are going to use synchronization to protect access to a shared variable, you must ensure that synchronization is used everywhere in the program where the variable is accessed.

Don't Overdo It

While threads can greatly simplify many types of applications, overuse of threads can jeopardize a program's performance and its maintainability. The thread consumed resources. Therefore, there is a limit to the number of threads that can be created without degrading performance.

Especially on a uniprocessor system, using multiple threads will not make programs that primarily consume CPU resources run faster.

Example: Use one thread for timing and another thread to complete the work

The following example uses two threads, one for timing and one for execution practical work. The main thread uses a very simple algorithm to calculate prime numbers.

Before it starts, it creates and starts a timer thread, which sleeps for ten seconds and then sets a flag that the main thread checks. 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);
            }
        }
    }
 
    public static void main(String[] args) {
        CalculatePrimes calculator = new CalculatePrimes();
        calculator.start();
        try {
            Thread.sleep(TEN_SECONDS);
        }
        catch (InterruptedException e) {
            // fall through
        }
 
        calculator.finished = true;
    }
}
Copy after login

Summary

The Java language includes powerful threading facilities built into the language. You can use threading tools to:

Increase the responsiveness of GUI applications

Take advantage of multi-processor systems

Simplify program logic when the program has multiple independent entities

Perform blocking I/O without blocking the entire program

When using multiple threads, care must be taken to follow the rules for sharing data between threads, which we will discuss in Sharing These rules are discussed in Access to Data. All these rules boil down to one basic principle: Don’t forget to synchronize.

The above is the detailed content of What is the use of java threads. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!