近期看一个音频传输代码时,对方采用了LinkedBlockingQueue为生产者、消费者模式,来支撑读写线程。

个人感觉非常不错,因此也对这种方式进行总结,并梳理了一个基本的功能框架备用。主要两点:

1、当对queue采用take操作时,若队列为空则阻塞;

2、当对queue采用put操作时,若队列为满则阻塞;

package com.fredric;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue; public class Buffer { private BlockingQueue<BufferData> queue; public static class BufferData { public byte mData[]; public BufferData() {
mData = new byte[100];
}
} public Buffer(int bufferSize) {
queue = new LinkedBlockingQueue<BufferData>(bufferSize);
} public BufferData doGet(){
if(null != queue){
try {
return (BufferData) queue.take();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return null;
} public boolean doPut(BufferData data){
try {
queue.put(data);
return true;
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return false;
}
}
package com.fredric;

public class Reader implements Runnable{

    Buffer buffer;

    public Reader(Buffer buffer){
this.buffer = buffer;
} @Override
public void run() { try {
Thread.sleep(500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(new String(buffer.doGet().mData)
+ " " + Thread.currentThread().getName());
}
}
package com.fredric;

import java.util.Date;
import java.util.concurrent.BlockingQueue; import com.fredric.Buffer.BufferData; public class Writer implements Runnable{ Buffer buffer; public Writer(Buffer buffer){
this.buffer = buffer;
} @Override
public void run() {
BufferData temp = new BufferData();
String str = new Date().toString();
System.arraycopy(str.getBytes(), 0, temp.mData, 0, str.getBytes().length); if(true == buffer.doPut(temp)){
System.out.println(" Thread Name: " + Thread.currentThread().getName());
}
}
}
package com.fredric;

public class App {

    public static void main(String[] args){

        Buffer buffer = new Buffer(2);

        Writer writer = new Writer(buffer);
Reader reader = new Reader(buffer); for (int i = 0; i < 5; i++) {
new Thread(writer, "writer " + (i + 1)).start(); new Thread(reader, "reader " + (i + 1)).start();
}
}
}
05-11 16:00