用Java代码实现:现有A、B两个线程,文件夹S中有10张图片,图片名分别为a1.jpg或a1.png、b2.jpg或b2.png、c3..d4..以此类推..k10.jpg或k10.png,A线程任务是往文件夹D中拷贝图片,B线程任务是每有一张图片拷贝进来,需将图片名称改成1.jpg或1.png。。以此类推到10.png或10.jpg,然后程序退出。要求:A线程不能一次拷贝多张图片,B线程不能一次修改多张图片名,即模拟生产者、消费者,拷贝进一个,修改一个名称
时间: 2023-07-14 21:14:31 浏览: 51
下面是用 Java 代码实现的生产者消费者模型,其中 A 线程作为生产者,B 线程作为消费者。
```java
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.StandardCopyOption;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
public class Main {
private static final int NUM_IMAGES = 10;
public static void main(String[] args) {
BlockingQueue<File> queue = new LinkedBlockingQueue<>(NUM_IMAGES);
Thread producer = new Thread(new ImageProducer(queue), "Producer");
Thread consumer = new Thread(new ImageConsumer(queue), "Consumer");
producer.start();
consumer.start();
try {
producer.join();
consumer.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
class ImageProducer implements Runnable {
private static final String SRC_DIR = "S/";
private static final String DEST_DIR = "D/";
private final BlockingQueue<File> queue;
public ImageProducer(BlockingQueue<File> queue) {
this.queue = queue;
}
@Override
public void run() {
for (int i = 1; i <= Main.NUM_IMAGES; i++) {
File srcFile = new File(SRC_DIR + getFilename(i));
File destFile = new File(DEST_DIR + getFilename(i));
try {
Files.copy(srcFile.toPath(), destFile.toPath(),
StandardCopyOption.REPLACE_EXISTING);
queue.put(destFile); // 添加到队列中
System.out.println("Produced: " + destFile.getName());
} catch (IOException | InterruptedException e) {
e.printStackTrace();
}
try {
Thread.sleep(1000); // 模拟拷贝过程
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
private String getFilename(int index) {
char c = (char) ('a' + index - 1);
return String.format("%c%d.%s", c, index, index % 2 == 0 ? "jpg" : "png");
}
}
class ImageConsumer implements Runnable {
private static final String DEST_DIR = "D/";
private final BlockingQueue<File> queue;
public ImageConsumer(BlockingQueue<File> queue) {
this.queue = queue;
}
@Override
public void run() {
for (int i = 1; i <= Main.NUM_IMAGES; i++) {
try {
File file = queue.take(); // 从队列中取出文件
File newFile = new File(DEST_DIR + i + "." + getFileExtension(file));
if (file.renameTo(newFile)) {
System.out.println("Consumed: " + newFile.getName());
} else {
System.err.println("Failed to rename file: " + file.getName());
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
private String getFileExtension(File file) {
String name = file.getName();
int idx = name.lastIndexOf(".");
return idx >= 0 ? name.substring(idx + 1) : "";
}
}
```
程序的执行过程如下:
1. A 线程从文件夹 S 中逐一拷贝图片到文件夹 D,每次拷贝完成后将文件添加到队列中。
2. B 线程从队列中取出文件,按照题目要求将文件名修改为 1.jpg 或 1.png,然后输出修改后的文件名。
3. A、B 线程交替执行,直到所有图片都被拷贝并修改完毕,程序退出。