示例:
import lombok.extern.slf4j.Slf4j;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
@Slf4j
public class ReadAndWriteMain {
private static final ReentrantReadWriteLock LOCK = new ReentrantReadWriteLock();
private static int num = 0;
private static void op(Lock lock, boolean read) {
try {
lock.lock();
Thread.sleep(1000L);
if (read) {
log.info("thread-id:{}\t读操作\tnum:{}", Thread.currentThread().getId(), num);
} else {
log.info("thread-id:{}\t写操作\tnum:{}", Thread.currentThread().getId(), ++num);
}
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
public static class ReadThread implements Runnable {
@Override
public void run() {
op(LOCK.readLock(), true);
}
}
public static class WriteThread implements Runnable {
@Override
public void run() {
op(LOCK.writeLock(), false);
}
}
private static ThreadFactory factory = Thread::new;
private static ThreadPoolExecutor exec =
new ThreadPoolExecutor(10, 10, 5L, TimeUnit.SECONDS,
new ArrayBlockingQueue<>(10),
factory);
public static void main(String[] args) {
long st = System.currentTimeMillis();
int n = 5;
for (int i = 0; i < n; i++) {
exec.execute(new ReadThread());
exec.execute(new ReadThread());
// exec.execute(new WriteThread());
}
quit(st);
}
private static void quit(long st) {
exec.shutdown();
while (true) {
if (exec.isTerminated()) {
log.info("执行耗时: {}ms", (System.currentTimeMillis() - st));
return;
}
}
}
}