search
HomeJavajavaTutorialHow to implement concurrent programming using multithreading in Java?

How to implement concurrent programming using multithreading in Java?

Aug 06, 2023 pm 01:24 PM
Concurrent programmingjava multithreading

How to use multi-threading in Java to implement concurrent programming?

In the development of modern computer processors, we have seen the emergence of multi-core processors, which provide more possibilities for concurrent programming. As a widely used programming language, Java provides a rich multi-threading library to help developers achieve efficient concurrent programming. This article will introduce how to implement concurrent programming using multi-threading in Java and provide code examples.

  1. Two ways to create a thread

In Java, there are two ways to create a thread: inheriting the Thread class and implementing the Runnable interface.

Method 1: Inherit the Thread class

class MyThread extends Thread {
    @Override
    public void run() {
        System.out.println("MyThread is running");
    }
}

public class Main {
    public static void main(String[] args) {
        MyThread myThread = new MyThread();
        myThread.start();
    }
}

Method 2: Implement the Runnable interface

class MyRunnable implements Runnable {
    @Override
    public void run() {
        System.out.println("MyRunnable is running");
    }
}

public class Main {
    public static void main(String[] args) {
        MyRunnable myRunnable = new MyRunnable();
        Thread thread = new Thread(myRunnable);
        thread.start();
    }
}
  1. Synchronization and mutual exclusion

When many When multiple threads access shared resources at the same time, data inconsistency or other problems may occur. In order to avoid these problems, we need to ensure synchronization and mutual exclusion between threads. Java provides the synchronized keyword to achieve synchronization and mutual exclusion between threads.

class Counter {
    private int count = 0;

    public synchronized void increment() {
        count++;
    }

    public synchronized int getCount() {
        return count;
    }
}

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

        Thread thread1 = new Thread(() -> {
            for (int i = 0; i < 1000000; i++) {
                counter.increment();
            }
        });

        Thread thread2 = new Thread(() -> {
            for (int i = 0; i < 1000000; i++) {
                counter.increment();
            }
        });

        thread1.start();
        thread2.start();

        thread1.join();
        thread2.join();

        System.out.println("Count: " + counter.getCount());
    }
}

In the above code, we created a thread-safe counter class Counter, using the synchronized keyword to ensure the atomic operation of the increment() and getCount() methods. In the main() method, we create two threads to increment the counter value and finally output the counter value.

  1. Communication between threads

Multiple threads may need to communicate. Java provides methods such as wait(), notify() and notifyAll() to achieve this. Communication between threads.

class Message {
    private String content;
    private boolean empty = true;

    public synchronized String read() {
        while (empty) {
            try {
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        empty = true;
        notifyAll();
        return content;
    }

    public synchronized void write(String content) {
        while (!empty) {
            try {
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        empty = false;
        this.content = content;
        notifyAll();
    }
}

public class Main {
    public static void main(String[] args) {
        Message message = new Message();

        Thread producer = new Thread(() -> {
            String[] contents = {"Message 1", "Message 2", "Message 3"};
            for (String content : contents) {
                message.write(content);
            }
        });

        Thread consumer = new Thread(() -> {
            for (int i = 0; i < 3; i++) {
                System.out.println("Message received: " + message.read());
            }
        });

        producer.start();
        consumer.start();
    }
}

In the above code, we created a Message class to store messages. The read() method waits when the message is empty and does not return until a new message is written. The write() method waits when the message is not empty and continues writing new messages until the message is read.

  1. Thread Pool

In actual applications, creating and destroying threads is a very resource-consuming operation, and the thread pool can reuse threads and control the number of threads, improving resources. Utilization. Java provides the ThreadPoolExecutor class to implement thread pools.

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class Main {
    public static void main(String[] args) {
        ExecutorService executor = Executors.newFixedThreadPool(5);

        for (int i = 0; i < 10; i++) {
            executor.submit(() -> {
                System.out.println("Task executed by " + Thread.currentThread().getName());
            });
        }

        executor.shutdown();
    }
}

In the above code, we created a thread pool containing 5 threads and submitted 10 tasks to the thread pool for execution. Finally, we need to call the executor.shutdown() method to shut down the thread pool.

Summary:

This article introduces how to use multi-threading in Java to implement concurrent programming and provides corresponding code examples. By using multiple threads and performing synchronization, mutual exclusion, and inter-thread communication, we can achieve efficient concurrent programming. At the same time, using the thread pool can also improve resource utilization and program performance. I hope this article helps you understand concurrent programming.

The above is the detailed content of How to implement concurrent programming using multithreading in Java?. 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)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

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.

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)