我有两个Runnable
班,Reader
和Writer
。
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.util.concurrent.Exchanger;
public class Reader implements Runnable {
private static final int THRESHHOLD = 1000;
private final int START, STOP;
private Exchanger<ByteBuffer> exch;
private RandomAccessFile file;
private ByteBuffer buffer;
public Reader(Exchanger<ByteBuffer> ex, RandomAccessFile f, int start, int stop) {
START = start;
STOP = stop;
exch = ex;
file = f;
buffer = ByteBuffer.allocate(THRESHHOLD);
buffer.mark();
}
@Override
public void run() {
for(int i = START; i < STOP; i++)
try {
buffer.put((byte)file.read());
} catch(IOException e) {
e.printStackTrace();
}
try {
exch.exchange(buffer);
} catch(InterruptedException e) {
e.printStackTrace();
}
}
}
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.util.concurrent.Exchanger;
import java.util.concurrent.locks.ReentrantLock;
public class Writer implements Runnable {
private static final int THRESHHOLD = 1000;
private final int START, STOP;
private ReentrantLock lock;
private Exchanger<ByteBuffer> exch;
private RandomAccessFile file;
private ByteBuffer buffer;
public Writer(Exchanger<ByteBuffer> e, ReentrantLock l, RandomAccessFile f, int start, int stop) {
lock = l;
START = start;
STOP = stop;
exch = e;
file = f;
}
@Override
public void run() {
try {
buffer = exch.exchange(ByteBuffer.allocate(THRESHHOLD));
} catch(InterruptedException e) {
e.printStackTrace();
}
lock.lock();
for(int i = START; i < STOP; i++)
try {
file.write(buffer.get());
} catch(IOException e) {
e.printStackTrace();
}
lock.unlock();
}
}
这两个线程都使用 anExchanger
来交换相同类型的数据。如何确保只在Reader
和Writer
线程之间进行交换,而不是在 smae 类型的两个线程之间进行?