search
HomeJavajavaTutorialWhat is the use of java threads

What is the use of java threads

May 08, 2019 pm 05:05 PM
java

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;
    }
}

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!

Statement
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
How does the class loader subsystem in the JVM contribute to platform independence?How does the class loader subsystem in the JVM contribute to platform independence?Apr 23, 2025 am 12:14 AM

The class loader ensures the consistency and compatibility of Java programs on different platforms through unified class file format, dynamic loading, parent delegation model and platform-independent bytecode, and achieves platform independence.

Does the Java compiler produce platform-specific code? Explain.Does the Java compiler produce platform-specific code? Explain.Apr 23, 2025 am 12:09 AM

The code generated by the Java compiler is platform-independent, but the code that is ultimately executed is platform-specific. 1. Java source code is compiled into platform-independent bytecode. 2. The JVM converts bytecode into machine code for a specific platform, ensuring cross-platform operation but performance may be different.

How does the JVM handle multithreading on different operating systems?How does the JVM handle multithreading on different operating systems?Apr 23, 2025 am 12:07 AM

Multithreading is important in modern programming because it can improve program responsiveness and resource utilization and handle complex concurrent tasks. JVM ensures the consistency and efficiency of multithreads on different operating systems through thread mapping, scheduling mechanism and synchronization lock mechanism.

What does 'platform independence' mean in the context of Java?What does 'platform independence' mean in the context of Java?Apr 23, 2025 am 12:05 AM

Java's platform independence means that the code written can run on any platform with JVM installed without modification. 1) Java source code is compiled into bytecode, 2) Bytecode is interpreted and executed by the JVM, 3) The JVM provides memory management and garbage collection functions to ensure that the program runs on different operating systems.

Can Java applications still encounter platform-specific bugs or issues?Can Java applications still encounter platform-specific bugs or issues?Apr 23, 2025 am 12:03 AM

Javaapplicationscanindeedencounterplatform-specificissuesdespitetheJVM'sabstraction.Reasonsinclude:1)Nativecodeandlibraries,2)Operatingsystemdifferences,3)JVMimplementationvariations,and4)Hardwaredependencies.Tomitigatethese,developersshould:1)Conduc

How does cloud computing impact the importance of Java's platform independence?How does cloud computing impact the importance of Java's platform independence?Apr 22, 2025 pm 07:05 PM

Cloud computing significantly improves Java's platform independence. 1) Java code is compiled into bytecode and executed by the JVM on different operating systems to ensure cross-platform operation. 2) Use Docker and Kubernetes to deploy Java applications to improve portability and scalability.

What role has Java's platform independence played in its widespread adoption?What role has Java's platform independence played in its widespread adoption?Apr 22, 2025 pm 06:53 PM

Java'splatformindependenceallowsdeveloperstowritecodeonceandrunitonanydeviceorOSwithaJVM.Thisisachievedthroughcompilingtobytecode,whichtheJVMinterpretsorcompilesatruntime.ThisfeaturehassignificantlyboostedJava'sadoptionduetocross-platformdeployment,s

How do containerization technologies (like Docker) affect the importance of Java's platform independence?How do containerization technologies (like Docker) affect the importance of Java's platform independence?Apr 22, 2025 pm 06:49 PM

Containerization technologies such as Docker enhance rather than replace Java's platform independence. 1) Ensure consistency across environments, 2) Manage dependencies, including specific JVM versions, 3) Simplify the deployment process to make Java applications more adaptable and manageable.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.