Home > Java > Java Tutorial > body text

How to implement concurrent programming using multithreading in Java?

PHPz
Release: 2023-08-06 13:24:20
Original
1327 people have browsed it

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();
    }
}
Copy after login

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();
    }
}
Copy after login
  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());
    }
}
Copy after login

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();
    }
}
Copy after login

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();
    }
}
Copy after login

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!

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!