示例:
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;
}
}
}
}
本文通过使用ReentrantReadWriteLock实现读写锁的并发控制,详细介绍了如何在多线程环境中进行资源的读写操作,确保数据的一致性和线程安全。通过示例代码展示了读线程和写线程的执行过程,以及如何利用线程池来管理这些线程。

被折叠的 条评论
为什么被折叠?



