static final ReadWriteLock lock = new ReentrantReadWriteLock(true);
static Executor executor = Executors.newFixedThreadPool(4);
public static void main(String[] args) {
//创建双读双写的线程
executor.execute(new Read());
executor.execute(new Read());
executor.execute(new Write());
executor.execute(new Write());
}
//读线程
static class Read implements Runnable {
public void run() {
for (int i = 0; i < 1000; i++) {
lock.readLock().lock();
for (int j = 0; j < 10; j++) {
ThreadUtil.sleep(1);
System.out.println(Thread.currentThread().getName()+"read"+j);
}
lock.readLock().unlock();
}
}
}
//写线程
static class Write implements Runnable {
public void run() {
for (int i = 0; i < 1000; i++) {
lock.writeLock().lock();
for (int j = 0; j < 10; j++) {
ThreadUtil.sleep(1);
System.out.println(Thread.currentThread().getName()+"write"+j);
}
lock.writeLock().unlock();
}
}
}
截取执行结果片段
pool-1-thread-4write0
pool-1-thread-4write1
pool-1-thread-4write2
pool-1-thread-4write3
pool-1-thread-4write4
pool-1-thread-4write5
pool-1-thread-4write6
pool-1-thread-4write7
pool-1-thread-4write8
pool-1-thread-4write9
pool-1-thread-3write0
pool-1-thread-3write1
pool-1-thread-3write2
pool-1-thread-3write3
pool-1-thread-3write4
pool-1-thread-3write5
pool-1-thread-3write6
pool-1-thread-3write7
pool-1-thread-3write8
pool-1-thread-3write9
pool-1-thread-2read0
pool-1-thread-1read0
pool-1-thread-2read1
pool-1-thread-1read1
pool-1-thread-2read2
pool-1-thread-1read2
pool-1-thread-2read3
pool-1-thread-1read3
pool-1-thread-2read4
pool-1-thread-1read4
pool-1-thread-2read5
pool-1-thread-1read5
pool-1-thread-2read6
pool-1-thread-1read6
pool-1-thread-2read7
pool-1-thread-1read7
pool-1-thread-2read8
pool-1-thread-1read8
pool-1-thread-2read9
pool-1-thread-1read9
读锁时 别的线程可以读不可以写
写锁时 别的线程不可以读 不可以写