我有两个线程 a和b,a生产图片,b消费图片,用bytebuffer存储图片,图片大小固定稳定
a 生产bytebuffer 0 b用0,把0清空
a如果发现0清空,把图片塞入0,0重复使用;a发现0被占用,把图片塞入bytebuffer 1 ,b的使用顺序是0,1
a如果发现0,1都被占用,把图片塞入bytebuffer 2,此时b的使用清空顺序是0,1,2
如果b把0,1,2,都清空后,发现1和2都没占用,接释放掉2的内存
后面以此类推,可以写个例子代码吗
package com.example.lib2;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.ByteBuffer;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
public class MyClass {
private final int buffer_size;
public MyClass(int BUFFER_SIZE) {
buffer_size = BUFFER_SIZE;
}
private final int MAX_BUFFERS = 5;
private final int MIN_FREE_BUFFERS = 2;
private final BlockingQueue<ByteBuffer> freeBuffers = new LinkedBlockingQueue<>();
private final BlockingQueue<ByteBuffer> filledBuffers = new LinkedBlockingQueue<>();
public void start() {
produce();
consume();
}
private void produce() {
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
try {
while (true) {
for (int i = 1; i <= 10; i++) {
if (filledBuffers.size() < MAX_BUFFERS) {
ByteBuffer buffer = freeBuffers.poll();
if (buffer == null) {
System.out.println("buffer allocate");
buffer = ByteBuffer.allocate(buffer_size);
} else {
buffer.clear();
}
String imagePath = "F:\\project\\jushi\\detect2-tensorrt\\sln\\x64\\Release\\dog.jpg";
File file = new File(imagePath);
byte[] bytes = new byte[(int) file.length()];
FileInputStream fis = new FileInputStream(file);
fis.read(bytes);
fis.close();
buffer.put(bytes);
buffer.flip();
filledBuffers.put(buffer);
}else {
System.out.println("filledBuffers full");
}
Thread.sleep(500); // 模拟生产过程
}
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
} catch (FileNotFoundException e) {
throw new RuntimeException(e);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
});
// 启动线程
thread.start();
}
private void consume() {
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
try {
while (true) {
ByteBuffer buffer = filledBuffers.take();
try {
OutputStream os = new FileOutputStream("image111.jpg");
byte[] data = new byte[buffer.remaining()];
buffer.get(data);
os.write(data);
os.close();
System.out.println("buffer get");
} catch (IOException e) {
throw new RuntimeException(e);
}
if (freeBuffers.size() < MIN_FREE_BUFFERS) {
buffer.clear();
freeBuffers.put(buffer);
}
Thread.sleep(10);
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
});
// 启动线程
thread.start();
}
public static void main(String[] args) {
int BUFFER_SIZE = 163759;
new MyClass(BUFFER_SIZE).start();
}
}