Home > Java > javaTutorial > body text

Introduction to concurrent programming technology in Java language

王林
Release: 2023-06-10 23:11:12
Original
1294 people have browsed it

Java is a programming language widely used to develop various programs, and its concurrent programming technology has received widespread attention. With the popularity of multi-core processors and the development of Web applications, the importance of concurrent programming in the Java language has become increasingly prominent. This article aims to introduce concurrent programming technology in the Java language.

1. What is concurrent programming

In computer science, concurrency refers to the phenomenon that two or more independent computing processes exist in a computer system at the same time. Concurrent programming refers to the programming technology for designing and implementing concurrent systems. The purpose is to solve the problem of multiple tasks executing within the same time period and improve the concurrency and efficiency of the system.

2. Threads in Java

In the Java language, threads are the basic component for managing concurrent applications. Java supports multi-threaded programming, that is, multiple threads can run simultaneously in one process.

The life cycle of a thread includes the stages of new creation, ready, running, blocking and death. In the Java language, threads are created and managed through the Thread class and Runnable interface. The Thread class represents a thread object, and the Runnable interface represents the tasks to be performed by the thread object.

For example, to create a simple thread in Java, you can use the following code:

public class MyThread extends Thread {
    public void run() {
        // 线程要执行的代码
    }
}

public class Main {
    public static void main(String[] args) {
        // 创建线程对象
        MyThread thread = new MyThread();

        // 启动线程
        thread.start();
    }
}
Copy after login

In the above code, the MyThread class inherits from the Thread class and overrides the run method. In this method Specifies the code to be executed by the thread. In the Main class, a MyThread object is created and the thread is started through the start method.

3. Synchronization mechanism in Java

In multi-threaded programming, the problem of shared resources is a common problem. If multiple threads access the same shared resource at the same time, data inconsistency and security issues may occur. At this time, a synchronization mechanism needs to be used to solve these problems.

Java provides a variety of synchronization mechanisms, the most commonly used of which is the synchronized keyword. Using the synchronized keyword can ensure mutual exclusivity when multiple threads access shared resources.

For example, the sample code for using the synchronized keyword to ensure data security in Java is as follows:

public class Counter {
    private int count = 0;

    public synchronized void increment() {
        // 线程安全的加1操作
        count++;
    }

    public int getCount() {
        return count;
    }
}

public class Main {
    public static void main(String[] args) throws InterruptedException {
        Counter counter = new Counter();

        // 创建10个线程,每个线程对计数器执行100次加1操作
        for (int i = 0; i < 10; i++) {
            new Thread(() -> {
                for (int j = 0; j < 100; j++) {
                    counter.increment();
                }
            }).start();
        }

        // 等待所有线程执行完毕
        Thread.sleep(1000);

        // 输出计数器的值
        System.out.println("Count: " + counter.getCount());
    }
}
Copy after login

In the above code, the Counter class represents a counter object, and the increment method uses the synchronized key This method is guaranteed to be mutually exclusive. When multiple threads access the increment method at the same time, only one thread can execute the method. 10 threads are created in the Main class, and each thread performs 100 increment operations on the counter. Finally, output the value of the counter, which should be 1000.

4. Lock mechanism in Java

Lock is a mechanism that controls multi-threaded access to shared resources. Java provides a variety of lock mechanisms, the most commonly used of which is the ReentrantLock class.

The ReentrantLock class is a reentrant lock that can solve issues such as fairness, reentrancy and interruptibility. Using the ReentrantLock class can ensure mutual exclusion and atomicity of operations when multiple threads execute code.

For example, the sample code for using the ReentrantLock class to ensure data security in Java is as follows:

public class Counter {
    private int count = 0;
    private ReentrantLock lock = new ReentrantLock();

    public void increment() {
        lock.lock();
        try {
            // 线程安全的加1操作
            count++;
        } finally {
            lock.unlock();
        }
    }

    public int getCount() {
        return count;
    }
}

public class Main {
    public static void main(String[] args) throws InterruptedException {
        Counter counter = new Counter();

        // 创建10个线程,每个线程对计数器执行100次加1操作
        for (int i = 0; i < 10; i++) {
            new Thread(() -> {
                for (int j = 0; j < 100; j++) {
                    counter.increment();
                }
            }).start();
        }

        // 等待所有线程执行完毕
        Thread.sleep(1000);

        // 输出计数器的值
        System.out.println("Count: " + counter.getCount());
    }
}
Copy after login

In the above code, the Counter class represents a counter object, and the increment method uses the ReentrantLock class to ensure The method is mutually exclusive. When multiple threads access the increment method at the same time, only one thread can obtain the lock and execute the method. 10 threads are created in the Main class, and each thread performs 100 increment operations on the counter. Finally, output the value of the counter, which should be 1000.

  1. Summary

Java is a programming language widely used to develop various programs. With the popularity of multi-core processors and the development of Web applications, the Java language The importance of concurrent programming has become increasingly prominent. This article introduces the concurrent programming technology in the Java language, including threads, synchronization mechanisms and lock mechanisms. These technologies can help developers better manage and control shared resources in the multi-threaded programming process and ensure the correctness and performance of the program.

The above is the detailed content of Introduction to concurrent programming technology in Java language. For more information, please follow other related articles on the PHP Chinese website!

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!