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.
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(); } }
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.
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.
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!