Java并发的场景和实现代码
时间: 2023-12-06 13:45:19 浏览: 40
Java并发编程是指在多个线程同时运行时,对共享资源的访问和修改进行协调和管理,以确保程序的正确性和性能。
下面是几个常见的Java并发场景和相应的实现代码:
1. 生产者-消费者模型
生产者-消费者模型是一种常见的并发场景,它涉及到一个或多个生产者线程向一个共享的缓冲区中生产数据,同时一个或多个消费者线程从缓冲区中消费数据。为了协调生产者和消费者线程之间的访问和修改,需要使用锁、条件变量等并发控制机制。
以下是一个简单的生产者-消费者模型的Java实现代码:
```java
import java.util.LinkedList;
import java.util.Queue;
import java.util.Random;
public class ProducerConsumerExample {
public static void main(String[] args) {
Queue<Integer> buffer = new LinkedList<>(); // 缓冲区
int maxSize = 10; // 缓冲区最大容量
Thread producerThread = new Thread(new Producer(buffer, maxSize), "Producer");
Thread consumerThread = new Thread(new Consumer(buffer), "Consumer");
producerThread.start();
consumerThread.start();
}
static class Producer implements Runnable {
private Queue<Integer> buffer;
private int maxSize;
public Producer(Queue<Integer> buffer, int maxSize) {
this.buffer = buffer;
this.maxSize = maxSize;
}
@Override
public void run() {
while (true) {
synchronized (buffer) {
while (buffer.size() == maxSize) {
try {
buffer.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
Random random = new Random();
int number = random.nextInt(100);
buffer.add(number);
System.out.println("Produced " + number);
buffer.notifyAll();
}
}
}
}
static class Consumer implements Runnable {
private Queue<Integer> buffer;
public Consumer(Queue<Integer> buffer) {
this.buffer = buffer;
}
@Override
public void run() {
while (true) {
synchronized (buffer) {
while (buffer.isEmpty()) {
try {
buffer.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
int number = buffer.poll();
System.out.println("Consumed " + number);
buffer.notifyAll();
}
}
}
}
}
```
2. 线程池
线程池是一种管理线程的机制,它通过在应用程序启动时创建一定数量的线程并将它们放入池中,然后在应用程序运行期间重复使用这些线程,以避免因频繁创建和销毁线程而导致的性能问题。Java中提供了Executor和ThreadPoolExecutor两个类来实现线程池。
以下是一个简单的线程池的Java实现代码:
```java
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class ThreadPoolExample {
public static void main(String[] args) {
ExecutorService executor = Executors.newFixedThreadPool(5);
for (int i = 0; i < 10; i++) {
Runnable worker = new WorkerThread("Task " + i);
executor.execute(worker);
}
executor.shutdown();
while (!executor.isTerminated()) {}
System.out.println("All tasks completed");
}
static class WorkerThread implements Runnable {
private String taskName;
public WorkerThread(String taskName) {
this.taskName = taskName;
}
@Override
public void run() {
System.out.println(Thread.currentThread().getName() + " " + taskName + " is running");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + " " + taskName + " is completed");
}
}
}
```
3. CountDownLatch
CountDownLatch是一种同步工具,它允许一个或多个线程等待一组事件的完成。当CountDownLatch的计数器变为0时,等待线程可以继续执行。Java中提供了CountDownLatch类来实现这种同步机制。
以下是一个简单的CountDownLatch的Java实现代码:
```java
import java.util.concurrent.CountDownLatch;
public class CountDownLatchExample {
public static void main(String[] args) throws InterruptedException {
int n = 5;
CountDownLatch startSignal = new CountDownLatch(1);
CountDownLatch doneSignal = new CountDownLatch(n);
for (int i = 0; i < n; i++) {
new Thread(new Worker(startSignal, doneSignal)).start();
}
System.out.println("Workers are waiting for the start signal");
Thread.sleep(1000);
startSignal.countDown(); // 发送开始信号
System.out.println("Workers are started");
doneSignal.await(); // 等待所有任务完成
System.out.println("All tasks are completed");
}
static class Worker implements Runnable {
private final CountDownLatch startSignal;
private final CountDownLatch doneSignal;
public Worker(CountDownLatch startSignal, CountDownLatch doneSignal) {
this.startSignal = startSignal;
this.doneSignal = doneSignal;
}
@Override
public void run() {
try {
startSignal.await(); // 等待开始信号
System.out.println(Thread.currentThread().getName() + " is working");
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
doneSignal.countDown(); // 发送完成信号
}
}
}
}
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)