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 do I use Maven or Gradle for advanced Java project management, build automation, and dependency resolution?How do I use Maven or Gradle for advanced Java project management, build automation, and dependency resolution?Mar 17, 2025 pm 05:46 PM

The article discusses using Maven and Gradle for Java project management, build automation, and dependency resolution, comparing their approaches and optimization strategies.

How do I create and use custom Java libraries (JAR files) with proper versioning and dependency management?How do I create and use custom Java libraries (JAR files) with proper versioning and dependency management?Mar 17, 2025 pm 05:45 PM

The article discusses creating and using custom Java libraries (JAR files) with proper versioning and dependency management, using tools like Maven and Gradle.

How do I implement multi-level caching in Java applications using libraries like Caffeine or Guava Cache?How do I implement multi-level caching in Java applications using libraries like Caffeine or Guava Cache?Mar 17, 2025 pm 05:44 PM

The article discusses implementing multi-level caching in Java using Caffeine and Guava Cache to enhance application performance. It covers setup, integration, and performance benefits, along with configuration and eviction policy management best pra

How can I use JPA (Java Persistence API) for object-relational mapping with advanced features like caching and lazy loading?How can I use JPA (Java Persistence API) for object-relational mapping with advanced features like caching and lazy loading?Mar 17, 2025 pm 05:43 PM

The article discusses using JPA for object-relational mapping with advanced features like caching and lazy loading. It covers setup, entity mapping, and best practices for optimizing performance while highlighting potential pitfalls.[159 characters]

How does Java's classloading mechanism work, including different classloaders and their delegation models?How does Java's classloading mechanism work, including different classloaders and their delegation models?Mar 17, 2025 pm 05:35 PM

Java's classloading involves loading, linking, and initializing classes using a hierarchical system with Bootstrap, Extension, and Application classloaders. The parent delegation model ensures core classes are loaded first, affecting custom class loa

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

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.

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment