共享内存中文变乱码
定义了一个环形共享内存:messagestation
public static RingBuffer<String> messagestation = new RingBuffer<String>(10000);
问题是:中文字符串经过写入(add)、读出(get)操作之后变为乱码,get()和add()函数见下面RingBuffer的定义。
谁有好的解决方案啊?
package C3P0DB;
import java.nio.BufferUnderflowException;
import java.util.concurrent.Semaphore;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* 环形缓冲区
* @author root
*/
public class RingBuffer<T> {
private T[] buffer;
private int tail;
private int head;
public int N;
public static Semaphore inSemaphore = new Semaphore(10000);//Landong: input semaphore
public static Semaphore outSemaphore = new Semaphore(0);//Landong: output semaphore
@SuppressWarnings("unchecked")
public RingBuffer(int n) {
buffer = (T[]) new Object[n];
tail = 0;
head = 0;
N = 0;
}
public boolean isEmpty() {
return N == 0;
}
public int size() {
return N;
}
public void add(T toAdd) {
try {
inSemaphore.acquire();//获取写入令牌
} catch (InterruptedException ex) {
Logger.getLogger(RingBuffer.class.getName()).log(Level.SEVERE, null, ex);
}
head = head % buffer.length;
buffer[head++] = toAdd; // new character to add
N++;
outSemaphore.release();//释放读出令牌
}
public T get() {
try {
outSemaphore.acquire();//获取写入令牌
} catch (InterruptedException ex) {
Logger.getLogger(RingBuffer.class.getName()).log(Level.SEVERE, null, ex);
}
if (isEmpty()) {
throw new BufferUnderflowException();
}
T t = null;
t = (T) buffer[tail++];
N--;
tail = tail % buffer.length;
inSemaphore.release();//释放读出令牌
return t;
}
@Override
public String toString() {
return "CircularBuffer(size=" + buffer.length + ", head=" + head + ", tail=" + tail + ")";
}
}